[leetcode]669. Trim a Binary Search Tree(Python)

[leetcode]669. Trim a Binary Search Tree

题目描述

Category:Easy 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.
在这里插入图片描述在这里插入图片描述

题目理解

给定一棵二叉搜索树和最大最小值边界(L和R),修剪该二叉搜索树,使树中所有值均位于[L, R] (R >= L) 范围之内。可以改变树的根节点,返回修剪后二叉搜索树的新根节点。

解题思路

递归

如果root的值比R大,说明root以及其所有右节点都不在这个区间内,向左边搜索。如果root的值比L小,,说明root以及其所有左节点都不在这个区间内,向右边搜索。如果root正好在这个区间内,那么分别对它的左右子树进行裁剪。
思路借鉴:https://blog.csdn.net/fuxuemingzhu/article/details/83869684#_57

class Solution:
	# Runtime: 108ms 5.00%  MemoryUsage: 17MB 100.00%
    def trimBST(self, root: TreeNode, L: int, R: int) -> TreeNode:
        if not root:
            return None
        if root.val > R:
            return self.trimBST(root.left, L, R)
        elif root.val < L:
            return self.trimBST(root.right, L, R)
        else:
            root.left = self.trimBST(root.left, L, R)
            root.right = self.trimBST(root.right, L, R)
            return root

永远学不会递归的zz已上线

Time

2020.3.22 这时间???这是真实的???我懵了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值