669. 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
给定二叉搜索树,将最低和最高边界作为L和R,修剪树,使其所有元素位于[L,R](R> = L)中。您可能需要更改树的根,所以结果应该返回修剪的二叉搜索树的新根。
  1. class Solution(object):
  2. def trimBST(self, root, L, R):
  3. """
  4. :type root: TreeNode
  5. :type L: int
  6. :type R: int
  7. :rtype: TreeNode
  8. """
  9. if not root:
  10. return root
  11. if root.val < L:
  12. return self.trimBST(root.right, L, R)
  13. if root.val > R:
  14. return self.trimBST(root.left, L, R)
  15. root.left = self.trimBST(root.left, L, R)
  16. root.right = self.trimBST(root.right, L, R)
  17. return root






原文地址:https://www.cnblogs.com/xiejunzhao/p/7501610.html