Leetcode修剪二叉搜索树

123 阅读1分钟

Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情

一、题目描述

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

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

例1:

image.png

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

例2:

image.png

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

二、解题思路

总体的思路不困难,如果某个节点小于下界,那就把这个节点和它的左子树都剪掉,把它的右子树接上去继续剪,如果某个节点大于上界,那就把这个节点和它的右子树都剪掉,把它的左子树接上去继续剪。写出了如下代码:

var trimBST = function(root, low, high) {
    //初始化node节点和prev节点
    while(node){
        if(node.val<low){
            prev.left = node.right;
            node = node.right;
        }else{
            prev = node;
            node = node.left;
        }
    }

    while(node){
        if(node.val>high){
            prev.right = node.left;
            node = node.left;
        }else{
            prev = node;
            node = node.right;
        }
    }
};

但是在初始化node节点和prev节点时遇到了困难,root节点本身可能会被剪掉。在改进之后写出了AC代码。

三、AC代码

var trimBST = function(root, low, high) {
    if(!root) return null;
    if(root.val<low) return trimBST(root.right,low,high);
    if(root.val>high) return trimBST(root.left,low,high);
    root.left = trimBST(root.left,low,high);
    root.right = trimBST(root.right,low,high);
    return root;
};

四、总结

还是对递归应用得不够灵活。