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;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容