附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;
}
小结:二叉搜索树,使用递归,效率不高,待研究
网友评论