leetcode(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.
这里写图片描述

题目分析:对于递归而言,是指从某个模式来不停的返回,想好要每一步的操作,以根节点作为模式的触发点,也就是从根的模式来进行思考,考虑每一步是什么,然后返回什么比较合计。
还要利用搜索树的性质来进行处理。

python代码的实现:

class Solution(object):
    def trimBST(self, root, L, R):
        """
        :type root: TreeNode
        :type L: int
        :type R: int
        :rtype: TreeNode
        """
        if root == None:
            return None
        if root.val < L:
            node = self.trimBST(root.right, L, R)
            root = node
        elif root.val > R:                                          
            node = self.trimBST(root.left, L, R)
            root = node
        else:                           
            node = self.trimBST(root.left, L, R)
            root.left = node
            node = self.trimBST(root.right, L, R) 
            root.right = node
        return root
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值