0
点赞
收藏
分享

微信扫一扫

大数据中TopK问题

月孛星君 03-26 19:30 阅读 2

文章目录


题目描述

给你二叉搜索树的根节点 root ,同时给定最小边界low 和最大边界 high。通过修剪二叉搜索树,使得所有节点的值在[low, high]中。修剪树 不应该 改变保留在树中的元素的相对结构 (即,如果没有被移除,原有的父代子代关系都应当保留)。 可以证明,存在 唯一的答案 。

所以结果应当返回修剪好的二叉搜索树的新的根节点。注意,根节点可能会根据给定的边界发生改变。

示例 1:
在这里插入图片描述

输入:root = [1,0,2], low = 1, high = 2
输出:[1,null,2]
示例 2:
在这里插入图片描述

输入:root = [3,0,4,null,2,null,null,1], low = 1, high = 3
输出:[3,2,null,1]

提示:

树中节点数在范围 [1, 104] 内
0 <= Node.val <= 104
树中每个节点的值都是 唯一 的
题目数据保证输入是一棵有效的二叉搜索树
0 <= low <= high <= 104

代码

class Solution {
    //使用递归的方法
    public TreeNode trimBST(TreeNode root, int low, int high) {
        //递归出口
        if (root==null){
            return null;
        }
        //得到左右子树的结果
        TreeNode leftChild = trimBST(root.left,low,high);
        TreeNode rightChild = trimBST(root.right,low,high);
        root.left = leftChild;
        root.right = rightChild;
        //处理中间节点
        if (root.val<low){
            if (root.right==null){
                return null;
            }else {
                //右子树不为空就要看一下右子树在区间内吗
                if (root.right.val<low){
                    return null;
                }else {
                    return root.right;
                }
            }
        }

        if (root.val>high){
            if (root.left==null){
                return null;
            }else {
                if (root.left.val>high){
                    return null;
                }else {
                    return root.left;
                }
            }
        }
        return root;
    }
}
举报

相关推荐

0 条评论