LeetCode 938. 二叉搜索树的范围和
题目描述
给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。
示例 1:
输入:root = [10,5,15,3,7,null,18], low = 7, high = 15
输出:32
二叉搜索树的范围和
提示:
树中节点数目在范围 [1, 2 * 104] 内
1 <= Node.val <= 105
1 <= low <= high <= 105
所有 Node.val 互不相同
一、解题关键词
二叉树 范围查找
二、解题报告
1.思路分析
常规的树的遍历
2.时间复杂度
3.代码示例
/**
* 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 total = 0;
public int rangeSumBST(TreeNode root, int low, int high) {
if(null == root){return 0;}
//树的遍历 然后 递归外面进行值的计算
int val = root.val;
if(val >= low && val <= high){
total += val;
}
rangeSumBST(root.left,low,high);
rangeSumBST(root.right,low,high);
return total;
}
}
2.知识点