二叉搜索树的范围和

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

示例1:

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

示例2:

输入: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 int rangeSumBST(TreeNode root, int low, int high) {
        List<Integer> list = new ArrayList<Integer>();
        infixOrder(root,list);
        return he(root,low,high,list);
    }

    public int he(TreeNode root,int low,int high,List<Integer> list){
        int temp = 0;//记录范围和
        //循环遍历list集合
        for(int i=0;i < list.size();i++){
            //如果遍历出来的值在范围内,则相加
            if(list.get(i) >= low && list.get(i) <= high){
                temp = temp + list.get(i);
            }
        }
        return temp;
        
    }

    //中序遍历,将遍历结果存入list
    public void infixOrder(TreeNode root,List<Integer> list){
        if(root == null){
            return;
        }
        infixOrder(root.left,list);
        list.add(root.val);
        infixOrder(root.right,list);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值