1.Description
给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。
2.Example
输入:root = [10,5,15,3,7,null,18], low = 7, high = 15
输出:32
3.Solution
1.我的一般思路
直接进行dfs,通过一个全局变量来接收sum的值
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int sum = 0;
public int rangeSumBST(TreeNode root, int low, int high) {
dfs(root,low,high);
return sum;
}
public void dfs(TreeNode root, int low, int high) {
if(root==null) {
return;
}
dfs(root.left, low, high);
if(root.val>=low&&root.val<=high) {
sum += root.val;
}
dfs(root.right, low, high);
}
}
2.不设置全局变量并且考虑到题目是二叉搜索树
1.root 节点为空
返回 0。
2.root 节点的值大于high
由于二叉搜索树右子树上所有节点的值均大于根节点的值,即均大于 high,故无需考虑右子树,返回左子树的范围和。
3.root 节点的值小于 low
由于二叉搜索树左子树上所有节点的值均小于根节点的值,即均小于low,故无需考虑左子树,返回右子树的范围和。
4.root 节点的值在[low,high] 范围内
此时应返回 root 节点的值、左子树的范围和、右子树的范围和这三者之和。
class Solution {
public int rangeSumBST(TreeNode root, int low, int high) {
if (root == null) {
return 0;
}
if (root.val > high) {
return rangeSumBST(root.left, low, high);
}
if (root.val < low) {
return rangeSumBST(root.right, low, high);
}
return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high);
}
}
3.不使用递归,使用迭代/bfs
用一个队列 qq 存储需要计算的节点。每次取出队首节点时,若节点为空则跳过该节点
class Solution {
public int rangeSumBST(TreeNode root, int low, int high) {
int sum = 0;
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root);
while (!q.isEmpty()) {
TreeNode node = q.poll();
if (node == null) {
continue;
}
if (node.val > high) {
q.offer(node.left);
} else if (node.val < low) {
q.offer(node.right);
} else {
sum += node.val;
q.offer(node.left);
q.offer(node.right);
}
}
return sum;
}
}