首页 > 其他 > 详细

938. 二叉搜索树的范围和

时间:2020-05-21 17:00:09      阅读:62      评论:0      收藏:0      [点我收藏+]

地址:https://leetcode-cn.com/problems/range-sum-of-bst/

<?php
/**
938. 二叉搜索树的范围和
给定二叉搜索树的根结点 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


提示:

树中的结点数量最多为 10000 个。
最终的答案保证小于 2^31。
 */

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($value) { $this->val = $value; }
 * }
 */
class Solution {

    /**
     * @param TreeNode $root
     * @param Integer $L
     * @param Integer $R
     * @return Integer
     */
    function rangeSumBST($root, $L, $R) {
        if($root == null) return 0;
        if($root->val >$R) {
            return $this->rangeSumBST($root->left,$L,$R);
        }elseif($root->val <$L){
            return $this->rangeSumBST($root->right,$L,$R);
        }else{
            return $root->val+$this->rangeSumBST($root->left,$L,$R)+$this->rangeSumBST($root->right,$L,$R);
        }
    }

}

 

938. 二叉搜索树的范围和

原文:https://www.cnblogs.com/8013-cmf/p/12931491.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!