【二叉搜索树的范围和(938-java)】
2023-09-27 14:29:28 时间
二叉搜索树的范围和(938-java)
给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。
示例 1:
输入:root = [10,5,15,3,7,null,18], low = 7, high = 15
输出:32
public class LC249_938_rangeSumBST {
//二叉树
static int sum = 0;
public static int rangeSumBST(TreeNode root, int low, int high) {
//二叉树的中序遍历
if (root == null) {
return 0;
}
//判断大小情况
if (root.val < low) {
return rangeSumBST(root.right, low, high);
}
if (root.val > high) {
return rangeSumBST(root.left, low, high);
}
//返回最终结果
return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high);
}
public static void main(String[] args) {
TreeNode tree = TreeNode.createTree();
TreeNode.printTree(tree);
int i = rangeSumBST(tree, 2, 15);
System.out.println(i);
}
}