235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最低公共祖先(难)
2016-06-25 23:13
465 查看
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
[思路]
如果如果p,q 比root小, 则LCA必定在左子树, 如果p,q比root大, 则LCA必定在右子树. 如果一大一小, 则root即为LCA.
参考
http://blog.csdn.net/xudli/article/details/46838747
[思路]
如果如果p,q 比root小, 则LCA必定在左子树, 如果p,q比root大, 则LCA必定在右子树. 如果一大一小, 则root即为LCA.
/** * 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* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(root==NULL || p==NULL || q==NULL){ return NULL; } if(root->val>p->val && root->val>q->val){ return lowestCommonAncestor(root->left,p,q); }else if(root->val<p->val && root->val<q->val){ return lowestCommonAncestor(root->right,p,q); }else{ return root; } } };
参考
http://blog.csdn.net/xudli/article/details/46838747
相关文章推荐
- form的onsubmit事件--表单提交前的验证最佳实现方式
- JAVA的第一个程序
- oracle 分库分表(sharding)
- ECMAScript6
- Linux解决乱码问题以及查看文件编码方式
- android下拉刷新+左滑删除的实现(第一种方式)
- 框架标签
- Linux学习之软件包管理--简介
- 运动目标检测——研究现状
- liunx 系统 (ubuntu(优麒麟))如何 配置JDK的方法
- 2.2 处理机调度
- Extjs与json数据格式的混合使用
- 函数指针实战一
- 除法
- #Wireshark#关于实验应用抓包的结果
- TCP协议端口状态说明:CLOSE-WAIT、TIME-WAIT 、LISTENING、SYN_SENT、ESTABLISHED、LAST-ACK ...
- 【转】】CTO、技术总监、首席架构师的区别
- sql server 根据执行计划查询耗时操作
- Mac系统下,Hadoop 2.6.2 + Zookeeper 3.4.6 完全分布式配置
- 链式存储队列