欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

LeetCode——938. 二叉搜索树的范围和

程序员文章站 2022-04-02 10:21:20
题目描述:给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。提示:树中节点数目在范围 [1, 2 * 104] 内1 <= Node.val <= 1051 <= low <= high <= 105所有 Node.val 互不相同示例 1:输入:root = [10,5,15,3,7,null,18], low = 7, high = 15输出:32示例 2:输入:root = [10,5,15,3...

题目描述:

给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。

提示:

  • 树中节点数目在范围 [1, 2 * 104] 内
  • 1 <= Node.val <= 105
  • 1 <= low <= high <= 105
  • 所有 Node.val 互不相同

示例 1:
LeetCode——938. 二叉搜索树的范围和
输入:root = [10,5,15,3,7,null,18], low = 7, high = 15
输出:32

示例 2:
LeetCode——938. 二叉搜索树的范围和
输入:root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
输出:23

代码如下:

/**
 * 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 {
    public static int rangeSumBST(TreeNode root, int low, int high) {
        ArrayList<Integer> list = new ArrayList<>();
        mid(root, list);
        int ans = 0;
        for (Integer k : list) {
            if (k >= low && k <= high) {
                ans += k;
            }
        }
        return ans;
    }

    public static void mid(TreeNode root, ArrayList<Integer> list) {
        if (root == null) {
            return;
        }
        mid(root.left, list);
        list.add(root.val);
        mid(root.right, list);
    }
}

执行结果:
LeetCode——938. 二叉搜索树的范围和

本文地址:https://blog.csdn.net/FYPPPP/article/details/114272445