天天算法 LeetCode-938-二叉搜索树的范围和

栏目: 编程工具 · 发布时间: 6年前

内容简介:https://leetcode-cn.com/problems/range-sum-of-bst/给定二叉搜索树的根结点二叉搜索树保证具有唯一的值。

题目链接

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

题目描述

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

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

示例 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

-------------------机智的思考线-------------------

-------------------机智的思考线--------------------

-------------------机智的思考线-------------------

解题方案

思路

  • 标签:深度优先遍历
  • 题意:这个题字面含义很难理解,本意就是求出所有 X >= LX <= R 的值的和
  • 递归终止条件:
    • 当前节点为null时返回0
    • 当前节点 X < L 时则返回右子树之和
    • 当前节点 X > R 时则返回左子树之和
    • 当前节点 X >= LX <= R 时则返回:当前节点值 + 左子树之和 + 右子树之和
  • 注意点:通过判断X的大小能够避免遍历全部树的节点,比如下方的动图中,3这个值就没有必要遍历
天天算法 LeetCode-938-二叉搜索树的范围和
示例1动图

代码

/**
 * 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) {
        if (root == null) {
            return 0;
        }
        if (root.val < L) {
            return rangeSumBST(root.right, L, R);
        }
        if (root.val > R) {
            return rangeSumBST(root.left, L, R);
        }
        return root.val + rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R);
    }
}
复制代码

欢迎关注,加入天天算法群,共同成长

天天算法 LeetCode-938-二叉搜索树的范围和

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Cult of the Amateur

The Cult of the Amateur

Andrew Keen / Crown Business / 2007-6-5 / USD 22.95

Amateur hour has arrived, and the audience is running the show In a hard-hitting and provocative polemic, Silicon Valley insider and pundit Andrew Keen exposes the grave consequences of today’s......一起来看看 《The Cult of the Amateur》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

MD5 加密
MD5 加密

MD5 加密工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换