给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。
int res =0;
public int rangeSumBST(TreeNode root, int low, int high) {//递归DFS
dfs(root,low,high);
return res;
}
void dfs(TreeNode root,int low,int high){
if (root != null){
if (root.val >= low && root.val <= high){
res += root.val;
}
if (root.val > low){//注意这里是大于最小值
dfs(root.left,low,high);
}
if (root.val < high){//小于最大值
dfs(root.right,low,high);
}
}
}
public int rangeSumBST(TreeNode root, int low, int high) {//迭代式DFS
int ans =0;
LinkedList<TreeNode> list = new LinkedList<>();
list.add(root);
while (!list.isEmpty()){
TreeNode node = list.pop();
if (node != null){
if (node.val >= low && node.val <= high){
ans += node.val;
}
if (node.val > low){
list.push(node.left);
// list.addLast(node.left);
}
if (node.val < high){
list.push(node.right);
// list.addLast(node.right);
}
}
}
return ans;
}