leetcode 每日一题 235. Lowest Common Ancestor of a Binary Search Tree
来源:互联网 发布:sql server 百度网盘 编辑:程序博客网 时间:2024/05/01 14:31
题目中给的是求二叉搜索树的两个节点的共同祖先,因此相对简单
主要就是理解了二叉搜索树的左节点<根<右节点即可
因此把root和两个点的值比较一下可以得出结论
为了更加清楚,写的判断条件比较复杂,其实可以直接把return r这句放在else中执行,不需要写出条件
discuss中还有一些递归等方法,时间都差不多,不赘述了
class Solution {public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { TreeNode* r=root; if(r==NULL) return NULL; while(true){ if((r->val<=p->val&&r->val>=q->val)||(r->val<=q->val&&r->val>=p->val)) return r; else if(r->val<=p->val&&r->val<=q->val&&r->right!=NULL) r=r->right; else if(r->val>=p->val&&r->val>=q->val&&r->left!=NULL) r=r->left; } return r; }};
0 0
- 【leetcode每日一题】235.Lowest Common Ancestor of a Binary Search Tree
- leetcode 每日一题 235. Lowest Common Ancestor of a Binary Search Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- [leetcode] 235.Lowest Common Ancestor of a Binary Search Tree
- [LeetCode]235.Lowest Common Ancestor of a Binary Search Tree
- 【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree LeetCode
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- [LeetCode]235. Lowest Common Ancestor of a Binary Search Tree
- [LeetCode]235. Lowest Common Ancestor of a Binary Search Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- [leetcode] 235. Lowest Common Ancestor of a Binary Search Tree
- 【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree
- leetcode:235. Lowest Common Ancestor of a Binary Search Tree
- LeetCode *** 235. Lowest Common Ancestor of a Binary Search Tree
- LeetCode-235.Lowest Common Ancestor of a Binary Search Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- leetcode-235. Lowest Common Ancestor of a Binary Search Tree
- ViewPager实现Gallery画廊效果——仿慕课网app-求职路线计划-效果(一)
- Java中static修饰类的问题
- objective-c - 基础篇 - NSNumber与NSdate与NSExcetion
- 设计模式学习笔记——单例模式
- 实例变量和类变量的区别
- leetcode 每日一题 235. Lowest Common Ancestor of a Binary Search Tree
- Androdi Bug说明
- 【自分の総括】设计模式之工厂模式(实例分析)
- 开启mongodb服务以及查看数据库中的信息
- 多线程编程中的等待/通知机制和等待超时模式
- 机房收费——存储过程+事务
- Java的接口
- Android自定义控件系列案例【四】
- Ubuntu 网络设置