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