leetcode(669):Trim a Binary Search Tree

news/2024/7/6 4:02:55 标签: leetcode

题目: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

http://www.niftyadmin.cn/n/1798840.html

相关文章

Linux-nat与nat

一、Linux-nat1、SANT应用环境&#xff1a;2、SNAT原理图3、SNAT实现步骤4、网关使用动态公网IP5、DNAT应用环境&#xff1a;6、DNAT原理7、DNAT使用步骤8、使用DNAT修改端口号二、真实路由器-nat1、分类&#xff1a;a、静态NAT(一个内部地址对应一个唯一的外部地址&#xff0c…

C++ STL string类相关

之所以抛弃char*的字符串而选用C标准程序库中的string类&#xff0c;是因为他和前者比较起来&#xff0c;不必 担心内存是否足够、字符串长度等等&#xff0c;而且作为一个类出现&#xff0c;他集成的操作函数足以完成我们大多数情况下(甚至是100%)的需要。我们可以用 进行赋值…

leetcode(404):Sum of Left Leaves

题目&#xff1a;Find the sum of all left leaves in a given binary tree. example: 3 / \ 9 20 / \ 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. 题目分析&#xff1a;求所有左叶子节点的和&#xff0c;然后…

WPF支持GIF的各种方法

2012.12.18更新&#xff1a;修复下载链接 已知WPF的Image元素只能显示GIF图片的第一帧&#xff0c;而MediaElement不能加载作为资源或内嵌的资源的GIF图片&#xff0c;所以网上有几种实现方法。 我抄袭网上提供的方法&#xff0c;改头换面后作为自己的GifImage实现。本文的前半…

简单认识LVS-DR负载群集和部署实例

文章目录 一、LVS-DR负载群集简介1、DR模式数据包流向分析2、DR 模式的特点 二、DR模式 LVS负载均衡群集部署 一、LVS-DR负载群集简介 1、DR模式数据包流向分析 1、客户端发送请求到 Director Server&#xff08;负载均衡器&#xff09;&#xff0c;请求的数据报文&#xff0…

leetcode(226):Invert Binary Tree

题目要求&#xff1a; 题目分析&#xff1a;还是利用树的递归的实现方法&#xff0c;也就是找一个模式&#xff0c;从根出发&#xff0c;然后执行操作&#xff0c;什么情况下停止操作&#xff0c;返回什么值&#xff0c;然后递归的实现左子树&#xff0c;右子树。 python代…

CentOS访问Windows共享文件夹的两种方法

1 在地址栏中输入下面内容:smb://Windows IP/Share folder name&#xff0c;smb为Server Message Block协议的简称&#xff0c;是一种IBM协议&#xff0c;运行在TCP/IP协议之上。从Windows 95开始&#xff0c;Microsoft Windows都提供了Server和Client的SMB协议支持&#xff0c…

leetcode(606):Construct String from Binary Tree

题目要求&#xff1a;You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way. The null node needs to be represented by empty parenthesis pair “()”. And you need to omit all the empty parenth…