【Leetcode】938. Range Sum of BST

Topic Address:

https://leetcode.com/problems/range-sum-of-bst/

Given a binary search tree, give a fixed range [ L , R ] [L,R] , seeking in the tree at all numbers in this range and.

Divide and conquer. First determine whether the scope of the roots, if not, it can be a direct result of solving a subtree; otherwise calculate left and right subtrees in the range of the number and, coupled with the roots can be. code show as below:

public class Solution {
    public int rangeSumBST(TreeNode root, int L, int R) {
        if (root == null) {
            return 0;
        }
        
        if (root.val < L) {
            return rangeSumBST(root.right, L, R);
        } else if (root.val > R) {
            return rangeSumBST(root.left, L, R);
        } else {
            return rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R) + root.val;
        }
    }
}

class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int x) {
        val = x;
    }
}

time complexity THE ( n ) O (n) , space THE ( h ) O(h)

Published 354 original articles · won praise 0 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/105338318
BST