给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。
示例1:
输入:root = [10,5,15,3,7,null,18], low = 7, high = 15
输出:32
来源:力扣
链接:938.二叉搜索树的范围和
法一:采用深度优先搜索,因为二叉搜索树是中序遍历是有序的,因此通过中序遍历,以及判断来获得结果。
class Solution {
int res = 0;
public int rangeSumBST(TreeNode root, int low, int high) {
if (root == null) return 0;
rangeSumBST(root.left, low, high);
if (root.val >= low && root.val <= high)
{
res += root.val;
}
rangeSumBST(root.right, low, high);
return res;
}
}
法二:仍是采用深度优先搜索,只是使用了一定程度的剪枝操作。
- 当前节点为空时返回0;
- 当前节点cur.val < low时,返回右子树之和,因为右子树的值会大于当前节点的值;
- 当前节点cur.val > high时,返回左子树之和,因为左子树的值会小于当前节点;
- 当前节点cur.val >= low 且 cur.val <= high时则返回:当前节点值+左子树之和+右子树之和。
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);
}
}
法三:采用广度优先搜索。
class Solution {
public int rangeSumBST(TreeNode root, int low, int high) {
int res = 0;
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root);
while(!q.isEmpty())
{
TreeNode node = q.poll();
if (node == null)
{
continue;
}
if(node.val < low)
{
q.offer(node.right);
}
else if (node.val > high)
{
q.offer(node.left);
}
else
{
res += node.val;
q.offer(node.left);
q.offer(node.right);
}
}
return res;
}
}