Leetcode学习笔记:#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 int rangeSumBST(TreeNode root, int L, int R){
int ans = 0;
Stack<TreeNode> stack = new Stack();
stack.put(root);
while(!stack.empty()){
TreeNode ndoe = stack.pop();
if(node!=null){
if(L <= node.val && R >= node.val)
ans += node.val;
if(L < node.val)
stack.push(node.left);
if(node.val > R)
stack.push(node.right);
}
}
return ans;
}
思路:
迭代或递归都可以实现,这里采用迭代。
先从根节点开始前序遍历二叉树,判断节点是否在L和R的范围内,如果在,则加入ans。之后判断该节点是否还是大于L或者小于R,如果为true,说明该节点还可能有比它更小的且大于L的或者比它更大的小于R的value,插入stack继续下次遍历。