本文首发于 语雀文档

    重点:

    代码:

    1. /**
    2. * Definition for a binary tree node.
    3. * class TreeNode {
    4. * val: number
    5. * left: TreeNode | null
    6. * right: TreeNode | null
    7. * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
    8. * this.val = (val===undefined ? 0 : val)
    9. * this.left = (left===undefined ? null : left)
    10. * this.right = (right===undefined ? null : right)
    11. * }
    12. * }
    13. */
    14. function rangeSumBST(root: TreeNode | null, low: number, high: number): number {
    15. if (root === null) return 0
    16. let sum = 0
    17. const check = (root: TreeNode | null) => {
    18. if (root === null) return
    19. check(root.left)
    20. check(root.right)
    21. if (root.val >= low && root.val <= high) {
    22. sum = sum + root.val
    23. }
    24. }
    25. check(root.left)
    26. check(root.right)
    27. if (root.val >= low && root.val <= high) {
    28. sum = sum + root.val
    29. }
    30. return sum
    31. };