二叉搜索树的范围和_力扣笔记

给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。
示例1:
bst1
输入:root = [10,5,15,3,7,null,18], low = 7, high = 15
输出:32

来源:力扣
链接:938.二叉搜索树的范围和

法一:采用深度优先搜索,因为二叉搜索树是中序遍历是有序的,因此通过中序遍历,以及判断来获得结果。

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

法二:仍是采用深度优先搜索,只是使用了一定程度的剪枝操作。

  • 当前节点为空时返回0;
  • 当前节点cur.val < low时,返回右子树之和,因为右子树的值会大于当前节点的值;
  • 当前节点cur.val > high时,返回左子树之和,因为左子树的值会小于当前节点;
  • 当前节点cur.val >= low 且 cur.val <= high时则返回:当前节点值+左子树之和+右子树之和。
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);
    }
}

法三:采用广度优先搜索。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值