669. Trim a Binary Search Tree

Easy
Given a binary search tree and the lowest and highest boundaries as L
and R
, trim the tree so that all its elements lies in [L, R]
(R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.

Example 1:
Input:

  1 
 / \ 
0   2 

L = 1 R = 2

Output:

1  
 \
  2

Example 2:
Input:

   3 
  / \ 
 0   4
  \ 
   2
 / 
1 

L = 1 R = 3

Output:

    3 
   /  
  2
 / 
1

Discuss

这道题用preOrder和postOrder都能做,用preOrder做,就是先处理root. 看root是否在range里面,如果root.val < L, 那么包括root在内的root的左子树都可以被扔掉,直接返回修剪后的root.right; 如果root.val > R, 那么包括root在内的root的右子树都可以被扔掉,直接返回修剪后的root.left. 如果root在range里面,那么我们调用递归函数分别再去修建root的左右子树。整个顺序就是preOrder.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode trimBST(TreeNode root, int L, int R) {
        if (root == null){
            return null;
        }   
        if (root.val < L){
            return trimBST(root.right, L, R);
        }
        if (root.val > R){
            return trimBST(root.left, L, R);
        }
        root.left = trimBST(root.left, L, R);
        root.right = trimBST(root.right, L, R);
        return root;
    }
}

如果是postOrder做,那么我们最后才会去处理root. 我们就先把root的左右子树修剪好,再去看root是否在range里面。如果root.val < L,我们直接返回修剪后的右子树;如果root.val > R, 我们直接返回修剪后的左子树;如果root在范围里,我们直接返回root, 因为此时root的左右子树都已经被修剪好了。这就是postOrder.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode trimBST(TreeNode root, int L, int R) {
        if (root == null){
            return null;
        }    
        root.left = trimBST(root.left, L, R);
        root.right = trimBST(root.right, L, R);
        if (root.val < L){
            return root.right;
        }
        if (root.val > R){
            return root.left;
        }
        return root;
    }
}

你可能感兴趣的:(669. Trim a Binary Search Tree)