938. Range Sum of BST

附leetcode链接:https://leetcode.com/problems/range-sum-of-bst/
938. Range Sum of BST
Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).
The binary search tree is guaranteed to have unique values.

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

小结:二叉搜索树,使用递归,效率不高,待研究

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容