Skip to content
On this page

修剪二叉搜索树

Question

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

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

思路

image-20230614150121849

这份代码能够通过,但我并不是特别清楚其中的逻辑

js
var trimBST = function(root, low, high) {
    if(root===null) return root		//没有找到要修剪的节点
    root.left = trimBST(root.left, low, high)
    root.right = trimBST(root.right, low, high)
    if(root.val<low){       //找到要删除子树的根节点
        return root.right
    }
    if(root.val>high){
        return root.left
    }
    return root
};

一开始我写成这样是无法通过的

js
var trimBST = function(root, low, high) {
    if(root===null) return root		//没有找到要修剪的节点
    if(root.val<low){       //找到要删除子树的根节点
        return root.right
    }
    if(root.val>high){
        return root.left
    }
    root.left = trimBST(root.left, low, high)
    root.right = trimBST(root.right, low, high)
    return root
};

在代码随想录题解的帮助下

js
var trimBST = function(root, low, high) {
    if(root===null) return root
    root.left = trimBST(root.left, low, high)
    root.right = trimBST(root.right, low, high)
    if(root.val<low){       //找到要删除子树的根节点
        return trimBST(root.right, low, high)   // 寻找符合区间[low, high]的节点
    }
    if(root.val>high){
        return trimBST(root.left, low, high)    // 寻找符合区间[low, high]的节点
    }
    return root
};