LeetCode 235: Lowest Common Ancestor of a Binary Search Tree
2015-07-27 18:41
447 查看
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the
definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow
a node to be a descendant of itself).”
For example, the lowest common ancestor (LCA) of nodes
分析:
在二叉查找树种,寻找两个节点的最低公共祖先。
1、如果a、b都比根节点小,则在左子树中递归查找公共节点。
2、如果a、b都比根节点大,则在右子树中查找公共祖先节点。
3、如果a、b一个比根节点大,一个比根节点小,或者有一个等于根节点,则根节点即为最低公共祖先。
According to the
definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow
a node to be a descendant of itself).”
_______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5
For example, the lowest common ancestor (LCA) of nodes
2and
8is
6. Another example is LCA of nodes
2and
4is
2, since a node can be a descendant of itself according to the LCA definition.
分析:
在二叉查找树种,寻找两个节点的最低公共祖先。
1、如果a、b都比根节点小,则在左子树中递归查找公共节点。
2、如果a、b都比根节点大,则在右子树中查找公共祖先节点。
3、如果a、b一个比根节点大,一个比根节点小,或者有一个等于根节点,则根节点即为最低公共祖先。
class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (root == NULL) { return NULL; } int min = (p->val > q->val ? q->val:p->val); int max = (p->val > q->val ? p->val: q->val); if(max < root->val) return lowestCommonAncestor(root->left, p, q); if (min > root->val) { return lowestCommonAncestor(root->right, p, q); } return root; } };
相关文章推荐
- 枚举的使用
- Android - DownloadManager的使用
- SGU 390-Tickets(数位dp)
- Spring综合Struts2
- HTML—看完轻松入门
- 黑马程序员——10,线程
- HDU-2057 A+B Again
- 接收短信
- 图论加边算法--链式向前星
- AngularJS学习笔记(四)
- App Store 审核指南中文翻译
- iOS学习笔记--(c基础题9)
- leetcode oj 1
- 解决8080端口被占,Tomcat无法正常启动
- C/C++中的联合体union及CPU大小端判定
- 我的Android进阶之旅------>android:drawableLeft的用法
- Object-C 面向对象的三大特征
- android沉浸式状态栏
- RecyclerView实现瀑布流布局
- Android中Handler与Thread的区别