GuilinDev

Lc0938

05 August 2008

938. Range Sum of BST

给个树,找出其中大于等于low小于等于high的结点,全部加起来的值

随便一种遍历方式

Recursive

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int rangeSumBST(TreeNode root, int low, int high) {
        int result = 0;
        result += rangeSearch(root, low, high, result);
        return result;
    }

    public int rangeSearch(TreeNode node, int low, int high, int result) {
        if (node != null) {
            if ((low <= node.val) && (node.val <= high))
                result = result + node.val;
            if (node.left != null)
                result = rangeSearch(node.left, low, high, result);
            if (node.right != null)
                result = rangeSearch(node.right, low, high, result);
        }
        return result;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
    int result = 0;
    public int rangeSumBST(TreeNode root, int low, int high) {
        if (root == null) {
            return 0;
        }

        if (low > root.val) {
            rangeSumBST(root.right, low, high);
        } else if (high < root.val) {
            rangeSumBST(root.left, low, high);
        } else {
            rangeSumBST(root.left, low, high);
            rangeSumBST(root.right, low, high);
            result += root.val;
        }
        return result;
    }
}

Iterative

1