LeetCode "Lowest Common Ancestor of a BST"
2015-07-11 06:27
302 查看
First please note, it is BST. So it is about value compare.
And what if it is a general tree, not necessarily a BST?
class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(!root) return nullptr; int sm = std::min(p->val, q->val); int lg = std::max(p->val, q->val); if( (root->val > sm && root->val < lg) || (root->val == sm || root->val == lg)) return root; else if(root->val > lg) return lowestCommonAncestor(root->left, p, q); else if(root->val < sm) return lowestCommonAncestor(root->right, p, q); return nullptr; } };
And what if it is a general tree, not necessarily a BST?
// unsigend char as record typedef unsigned char uchar; class Solution { TreeNode *pret; uchar go(TreeNode *root, TreeNode* p, TreeNode *q) { if (!root) return 0; uchar rec = 0; rec |= (root == p) ? 0x1 : 0; rec |= (root == q) ? 0x2 : 0; uchar rleft = go(root->left, p, q); if(rleft ==0x3) { return 0x3; } if (rec && ((rec | rleft) == 0x3)) { pret = root; return 0x3; } uchar rright= go(root->right, p, q); if(rright ==0x3) return 0x3; if (rec && ((rec | rright) == 0x3)) { pret = root; return 0x3; } if ((rleft | rright )== 0x3) { pret = root; } return rec | rleft | rright; } public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { pret = nullptr; go(root, p, q); return pret; } };
相关文章推荐
- myeclipse+maven实现多模块项目struts+spring+mybatis
- 精品 德国 软件推荐 著名的光盘烧录软件 Nero
- 软件明明已经删除 控制面板里还有名称
- Windows 7或者 server 小技巧 添加 IIS和FTP 组件功能
- Windows 7或者 server 小技巧 添加 IIS和FTP 组件功能
- 3.Longest Substring Without Repeating Characters(string; KMP, DP)
- Alwasyon环境下增加数据文件需要注意的几点
- uplooking-C语言基础
- kafka 学习笔记(四)之Python客户端
- 在OEL 5.4 32bit上使用yum install命令遇到的问题
- Leetcode NO.234 Palindrome Linked List
- 【MATLAB】Machine Learning (Coursera Courses Outline & Schedule)
- apk 反编译工具的使用
- knockout.js实例二~购物车
- java 多线程Echo server和client 例子
- 分享一个LiteDB做的简单考试系统辅助工具
- Kafka 学习笔记(三)之Java Consumer客户端
- WebGL 入门-模型导出
- PB Post到PHP接口时无法从_POST数组取值
- 考研总结