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

  正確方法其實應該是在遍歷的過程中就修改二叉樹,移除不合題意的結點。當然對於二叉樹的題,十有八九都是要用遞迴來解的。首先判斷如果root為空,那麼直接返回空即可。然後就是要看根結點是否在範圍內,如果根結點值小於L,那麼返回對其右子結點呼叫遞迴函式的值;如果根結點大於R,那麼返回對其左子結點呼叫遞迴函式的值。如果根結點在範圍內,將其左子結點更新為對其左子結點呼叫遞迴函式的返回值,同樣,將其右子結點更新為對其右子結點呼叫遞迴函式的返回值。最後返回root即可,參見程式碼如下:

/**
* 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 > R){
return trimBST(root.left, L, R);
}
else if(root.val < L){
return trimBST(root.right, L, R);
}
root.left = trimBST(root.left, L, R);
root.right = trimBST(root.right, L, R);
return root; }
}