Given the root node of a binary search tree, return the sum of values of all nodes with a value in the range [low, high].
Example 1:
Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32
Constraints:
The number of nodes in the tree is in the range [1, 2 * 104].
1 <= Node.val <= 105
1 <= low <= high <= 105
All Node.val are unique.
把BST中在[low, high]范围内的节点求和
思路:
和669题类似,669是把范围外的修剪掉。
BST的特征是左子树节点值 < root值 < 右子树节点值
可用中序遍历实现,中序遍历是升序排列的,所以中间满足条件的节点值直接相加即可。
class Solution {
int res = 0;
public int rangeSumBST(TreeNode root, int low, int high) {
inOrder(root, low, high);
return res;
}
void inOrder(TreeNode root, int low, int high) {
if(root == null) return;
inOrder(root.left, low, high);
if(root.val >= low && root.val <= high) res += root.val;
inOrder(root.right, low, high);
}
}
如果root.val < low的话,那么整个左子树和root都pass,只需要返回对右子树求和的结果。同理root.val > high时,整个右子树和root都不考虑,只要返回对左子树求和的结果。
如果root.val在范围内,那把root.val加到结果,然后继续对它的左子树和右子树求和。
节点是null时返回null。
递归实现
public int rangeSumBST(TreeNode root, int low, int high) {
if(root == null) return 0;
if(root.val >= low && root.val <= high) {
return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high);
} else if(root.val < low) {
return rangeSumBST(root.right, low, high);
}
return rangeSumBST(root.left, low, high);
}