Leetcode669-Trim a Binary Search Tree-Easy

题目:Trim a Binary Search Tree

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


 思路:
BST的特性:left < root < right
case 1: 如果root.val < L, 则返回修剪后的右子树 (把root 和左子树都裁掉:左子树的所有值一定小于L)
case 2: 如果root.val > R, 则返回修剪后的左子树 (裁掉root 和 右子树)
case 3: 如果 root.val 在范围内,那么保留root结点本身, 并且root.left = 修剪后的左子树, root.right = 修剪后的右子树。
 
代码:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode trimBST(TreeNode root, int L, int R) {
        if (root == null) return root;
        
        if (root.val < L) return trimBST(root.right, L, R);
        
        if (root.val > R) return trimBST(root.left, L, R);
        // 要把修剪过后的左右子树赋值给root.left root.right
        root.left = trimBST(root.left, L, R);
        root.right = trimBST(root.right, L, R);
        return root;
    }
}
原文地址:https://www.cnblogs.com/Jessiezyr/p/13437229.html