938. Range Sum of BST

dfs inorder

time:O(n), space:O(1)

global variable

class Solution {
    int sum = 0;
    public int rangeSumBST(TreeNode root, int low, int high) {
        inorder(root, low, high);
        return sum;
    }
    
    private void inorder(TreeNode root, int low, int high) {
        if (root == null) {
            return;
        }
        rangeSumBST(root.left, low, high);
        if (root.val >= low && root.val <= high) {
            sum += root.val;
        }
        rangeSumBST(root.right, low, high);
    }
    
}

divide and conquer

stack

Last updated

Was this helpful?