1. 题目:
给定二叉搜索树的根结点 root,返回 L 和 R(含)之间的所有结点的值的和。二叉搜索树保证具有唯一的值。
示例1:
输入:root = [10,5,15,3,7,null,18], L = 7, R = 15
输出:32
示例2:
输入:root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
输出:23
2. 思路:
根据题意,求中序遍历之后,两节点之间得值和.
3. 代码:
public static int rangeSumBST(TreeNode root, int L, int R) {
TreeNode curNode = root;
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
//先中序遍历
int flag = -1;
int result = 0;
while (curNode!=null || !stack.empty()){
while (curNode!= null ){
stack.push(curNode);
curNode = curNode.left;
}
if (!stack.empty()){
curNode = stack.pop();
if (curNode.val == L){
flag = 1;
}
if (flag == 1){
result+=curNode.val;
}
if (curNode.val == R){
flag = -1;
}
curNode = curNode.right;
}
}
return result;
}