博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode算法:Trim a Binar Search Tree
阅读量:4310 次
发布时间:2019-06-06

本文共 1234 字,大约阅读时间需要 4 分钟。

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之间 思想: 二叉排序树的特点是:对于任意一个节点,左子树任意节点数值都比跟节点小,右子树任意节点数值都比根大 所以考虑,对于任意一个节点, 如果值比l还小,那就应该抛弃这个根,去右子树寻找新的根 如果值比r还大,那就应该抛弃这个根,去左子树寻找新的根 这样的操作进行递归就可以了 我的python代码:
1 # Definition for a binary tree node. 2 class TreeNode: 3     def __init__(self, x): 4         self.val = x 5         self.left = None 6         self.right = None 7  8 class Solution: 9     def trimBST(self, root, L, R):10         """11         :type root: TreeNode12         :type L: int13         :type R: int14         :rtype: TreeNode15         """16         if root is None:17             return None18         if root.val >R:19             return self.trimBST(root.left ,L,R)20         if root.val

 

 

转载于:https://www.cnblogs.com/Lin-Yi/p/7501855.html

你可能感兴趣的文章
Anaconda+django写出第一个web app(八)
查看>>
模拟 HDOJ 5099 Comparison of Android versions
查看>>
关于http的post传送文件
查看>>
eclipse 快速导入所有需要的包
查看>>
枚举类
查看>>
关于ES6新特性
查看>>
Linux——变色的文件文件夹含义
查看>>
Android异常分析(转)
查看>>
php常用正则表达式
查看>>
ie7浏览器兼容问题
查看>>
matplotlib动态图subplots()和subplot()不同及参数
查看>>
python,shell,locale,charset
查看>>
CSS基础知识点笔记
查看>>
2016中国大学生程序设计竞赛(长春)-重现赛 1010Ugly Problem 回文数 模拟
查看>>
冒泡、选择、插入排序
查看>>
从小白到区块链工程师:第一阶段:Go语言的控制台输入和输出(3)
查看>>
iOS开发系列--通知与消息机制
查看>>
16.jQuery属性操作
查看>>
sonar安装
查看>>
使用chrome开发者工具中的performance面板解决性能瓶颈
查看>>