LeetCode 938. 二叉搜索树的范围和 easy/树,dfs

7 篇文章 0 订阅
4 篇文章 0 订阅


1.Description

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


2.Example

在这里插入图片描述

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

3.Solution

1.我的一般思路

直接进行dfs,通过一个全局变量来接收sum的值

/**
 * 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 {
	int sum = 0;
    public int rangeSumBST(TreeNode root, int low, int high) {
    	dfs(root,low,high);
    	return sum;
    }
    
    public void dfs(TreeNode root, int low, int high) {
    	if(root==null) {
    		return;
    	}
    	dfs(root.left, low, high);
    	if(root.val>=low&&root.val<=high) {
    		sum += root.val;
    	}
    	dfs(root.right, low, high);
    }
}

2.不设置全局变量并且考虑到题目是二叉搜索树

1.root 节点为空
返回 0。

2.root 节点的值大于high
由于二叉搜索树右子树上所有节点的值均大于根节点的值,即均大于 high,故无需考虑右子树,返回左子树的范围和。

3.root 节点的值小于 low
由于二叉搜索树左子树上所有节点的值均小于根节点的值,即均小于low,故无需考虑左子树,返回右子树的范围和。

4.root 节点的值在[low,high] 范围内
此时应返回 root 节点的值、左子树的范围和、右子树的范围和这三者之和。

class Solution {
    public int rangeSumBST(TreeNode root, int low, int high) {
        if (root == null) {
            return 0;
        }
        if (root.val > high) {
            return rangeSumBST(root.left, low, high);
        }
        if (root.val < low) {
            return rangeSumBST(root.right, low, high);
        }
        return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high);
    }
}

3.不使用递归,使用迭代/bfs

用一个队列 qq 存储需要计算的节点。每次取出队首节点时,若节点为空则跳过该节点

class Solution {
    public int rangeSumBST(TreeNode root, int low, int high) {
        int sum = 0;
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        q.offer(root);
        while (!q.isEmpty()) {
            TreeNode node = q.poll();
            if (node == null) {
                continue;
            }
            if (node.val > high) {
                q.offer(node.left);
            } else if (node.val < low) {
                q.offer(node.right);
            } else {
                sum += node.val;
                q.offer(node.left);
                q.offer(node.right);
            }
        }
        return sum;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值