669. Trim a Binary Search Tree 修剪二叉搜索树

本文介绍了一种算法,用于修剪二叉搜索树,确保其所有元素位于指定的最低和最高边界[L, R]内(R >= L)。通过递归地删除不符合条件的节点,调整树的结构,并返回修剪后的树的新根。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值