LeetCode笔记:669. Trim a Binary Search Tree
问题(Easy):
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:
Output:
Example 2: Input:
Output:
大意:
给出一个二叉查找树和最小、最大边界L和R,修剪树使其所有元素都在[L, R](R >= L)中。你可能需要改变树的根节点,所以结果应该返回裁剪后的树的新跟节点。 例1: 输入:
输出:
例2: 输入:
输出:
思路:
题目的意思就是让树只保留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 == NULL) return NULL;
TreeNode *res = root;
if (root->val > R)
res = trimBST(root->left, L, R);
else if (root->val < L)
res = trimBST(root->right, L, R);
else {
res->left = trimBST(res->left, L, R);
res->right = trimBST(res->right, L, R);
}
return res;
}
};
他山之石:
除了用递归,也可以用循环来做,就循环判断左右子树,看大小是否在范围内,在则继续往下,否则将其左/右子节点作为当前循环的节点。
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int L, int R) {
// find the proper root
while(root->val<L || root->val>R)
{
if(root->val<L) { root = root->right; }
else { root = root->left; }
}
// temporary pointer for left and right subtree
TreeNode *Ltemp = root;
TreeNode *Rtemp = root;
// remove the elements larger than L
while(Ltemp->left)
{
if( (Ltemp->left->val)<L ) { Ltemp->left = Ltemp->left->right; }
else { Ltemp = Ltemp->left; }
}
// remove the elements larger than R
while(Rtemp->right)
{
if( (Rtemp->right->val)>R) { Rtemp->right = Rtemp->right->left; }
else { Rtemp = Rtemp->right; }
}
return root;
}
};
合集:https://github.com/Cloudox/LeetCode-Record
相关文章
- 金融服务领域的大数据:即时分析
- 影响大数据、机器学习和人工智能未来发展的8个因素
- 从0开始构建一个属于你自己的PHP框架
- 如何将Hadoop集成到工作流程中?这6个优秀实践必看
- SEO公司使用大数据优化其模型的5种方法
- 关于Web Workers你需要了解的七件事
- 深入理解HTTPS原理、过程与实践
- 增强分析:数据和分析的未来
- PHP协程实现过程详解
- AI专家:大数据知识图谱——实战经验总结
- 关于PHP的错误机制总结
- 利用数据分析量化协同过滤算法的两大常见难题
- 怎么做大数据工作流调度系统?大厂架构师一语点破!
- 2019大数据处理必备的十大工具,从Linux到架构师必修
- OpenCV中的KMeans算法介绍与应用
- 教大家如果搭建一套phpstorm+wamp+xdebug调试PHP的环境
- CentOS下三种PHP拓展安装方法
- Go语言HTTP Server源码分析
- Go语言HTTP Server源码分析
- 2017年4月编程语言排行榜:Hack首次进入前五十