题目:

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) 。你可能需要改变树的根节点,所以结果应当返回修剪好的二叉搜索树的新的根节点。

二叉搜索树树的性质是,左子树上所有结点的值均小于它的根结点的值,右子树上所有结点的值均大于它的根结点的值,它的左、右子树也分别为二叉搜索树。

所以如果当前的节点的值小于L的话,我们就要递归执行当前节点的右子树,因为左子树上所有节点的值也均小于当前节点的值,自然也小于L。同理如果当前的节点的值大于R的话,就要递归执行当前节点的左子树,因为左子树上节点的值才可能在范围内。这两种情况当前节点都是需要改变的。之后递归执行左右子树即可。

程序:

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int L, int R) {
if(root == nullptr) return root;
if(root->val < L) return trimBST(root->right, L, R);
if(root->val > R) return trimBST(root->left, L, R); root->left = trimBST(root->left, L, R);
root->right = trimBST(root->right, L, R);
return root;
}
};

最新文章

  1. 升级xcode7.0 第三方库不能用的解决方法(bitcode是什么鬼?)
  2. SQL Server 无法在服务器上访问指定的路径或文件解决方法
  3. JS中级 - 01:DOM节点
  4. POJ 3450 后缀数组/KMP
  5. ASP.NET MVC使用input标签上传文件
  6. AJAX初步
  7. 【1-4】jQuery代码风格-导航栏
  8. 关于Swift中实现Lazy initialize的方式
  9. CentOS7安装Python3.5
  10. cas sso单点登录系列2:cas客户端和cas服务端交互原理动画图解,cas协议终极分析
  11. Retinex processing for automatic image enhancement 翻译
  12. 使用yum来下载RPM包而不进行安装
  13. Spring使用webjar
  14. SQL SERVER 查看占用tempDB
  15. Python脱产8期 Day08 2019/4/22
  16. jquery----Ajax补充
  17. 为什么Firefox在SSH上这么慢?
  18. mysql服务器iowait高优化一例完整深入解析
  19. @RequestMapping 介绍
  20. 如何使用Jfreechart生成柱状图?

热门文章

  1. 2019 SDN上机第三次作业
  2. 消息队列的使用&lt;一&gt;:介绍、使用场景和JMS概念知识
  3. 修改kile工程名字(转)
  4. JVM&NIO&HashMap简单问
  5. 随便读读skynet开源项目RILLSERVER
  6. Spring @CrossOrigin 通配符 解决跨域问题
  7. C# 嵌套循环
  8. C#写日志工具类
  9. Javaweb常用解决问题连接
  10. 构建maven项目,自定义目录结构方法