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

输入:root = [1,0,2], low = 1, high = 2
输出:[1,null,2]
思路:
注意返回值 return root;
class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        //1.修剪:root.val<low||root.val>high
        //2.调整(保证原结构)
        if(root==null){
            return null;
        }
        //(1)root.val>high//都在左边
        if(root.val>high){
            return trimBST(root.left, low, high);
        }
        //(2)root.val<low//都在右边
        if(root.val<low){
            return trimBST(root.right, low, high);
        }
        //(3)low<=root.val<=high//root在[low,high]范围内
        root.left = trimBST(root.left, low, high);//root.left接入符合条件的左孩子
        root.right = trimBST(root.right, low, high);//root.right接入符合条件的右孩子
        return root;
    }
}
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号