美文网首页
938. Range Sum of BST

938. Range Sum of BST

作者: 30岁每天进步一点点 | 来源:发表于2020-03-06 17:45 被阅读0次

    附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;
    }
    

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

    相关文章

      网友评论

          本文标题:938. Range Sum of BST

          本文链接:https://www.haomeiwen.com/subject/drywrhtx.html