leetcode 669. 修剪二叉搜索树


递归:

class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        if(root==null) return root;
        if(root.valhigh) return trimBST(root.left,low,high);
        else{
            root.left=trimBST(root.left,low,high);
            root.right=trimBST(root.right,low,high);
            return root;
        }
    }
}

迭代:

class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        while(root!=null&&(root.valhigh)){
            if(root.valhigh){
                cur.right=cur.right.left;
            }
            cur=cur.right;
        }
        return root;
    }
}

相关