力扣——二叉树的范围和

给定二叉搜索树的根结点 root,返回 L 和 R(含)之间的所有结点的值的和。

二叉搜索树保证具有唯一的值。

 

示例 1:

输入:root = [10,5,15,3,7,null,18], L = 7, R = 15
输出:32

示例 2:

输入:root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
输出:23

 

提示:

  1. 树中的结点数量最多为 10000 个。
  2. 最终的答案保证小于 2^31
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int rangeSumBST(TreeNode root, int L, int R) {
        int t1=0;
        //left
        int t2=0;
        //right
        int t3=0;
        if(root==null||L>R)
        {
            return 0;
        }
        if(root.val<=R&&root.val>=L)
        {
            t1+=root.val;
        }
        //如果根节点比最小值小,就不用去考虑其左子树
        if(root.val>=L&&root.left!=null)
        {
            t2+=rangeSumBST(root.left,L,R);
        }
         //如果根节点比最大值大,就不用去考虑其右子树
        if(root.val<=R&&root.right!=null)
        {
            t3+=rangeSumBST(root.right,L,R);        
    }
        return t1+t2+t3;
    }

}

 

posted @ 2019-02-10 18:07  JAYPARK01  阅读(147)  评论(0)    收藏  举报