669. 修剪二叉搜索树

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/trim-a-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


删除不再范围内的节点,依旧是回溯。返回到该节点时,如果该节点的值是合法的,拼接左右子树,返回该节点;如果大于最大的;那么返回左子树,因为右孩子一定是不再范围的,一定是null。如果小于最小的。那么返回右子树,因为左子树一定是不再范围的,返回null;

  public TreeNode trimBST(TreeNode root, int low, int high) {

        if(root == null) {
            return null;
        }

        TreeNode left = trimBST(root.left,low,high);
        TreeNode right = trimBST(root.right,low,high);

        root.left = left;
        root.right = right;
        // 该值合法,直接返回
        if(root.val >=low && root.val <= high) {
            return root;
        } else if(root.val < low) {
            return right;
        } else {
            return left;
        }

       

    }
posted @ 2022-02-23 18:30  一颗青菜  阅读(2)  评论(0)    收藏  举报