938. 二叉搜索树的范围和(DFS,BFS)
解法一:
DFS:中序遍历二叉搜索树
private int sum = 0;
public int rangeSumBST(TreeNode root, int low, int high) {
if(root == null) return 0;
//如果在区间里,则加上这个节点的值
if(root.val >= low && root.val <= high) {
sum += root.val;
if(root.left != null) rangeSumBST(root.left, low, high);
if(root.right != null) rangeSumBST(root.right, low, high);
} else if(root.val < low) {
//如果小于这个区间,则递归检测该节点的右节点
if(root.right != null) rangeSumBST(root.right, low, high);
} else {
//如果大于这个区间,则递归检测该节点的左节点
if(root.left != null) rangeSumBST(root.left, low, high);
}
return sum;
}
解法二:
BFS:层序遍历二叉搜索树
public int rangeSumBST(TreeNode root, int low, int high) {
int sum = 0;
if(root == null) return 0;
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.add(root);
while(!q.isEmpty()) {
int size = q.size();
for(int i = 0; i < size; i++) {
TreeNode node = q.poll();
if(node.val >= low && node.val <= high) {
sum += node.val;
if(node.left != null) q.add(node.left);
if(node.right != null) q.add(node.right);
} else if(node.val < low) {
if(node.right != null) q.add(node.right);
} else {
if(node.left != null) q.add(node.left);
}
}
}
return sum;
}