LeetCode OJ 之 Lowest Common Ancestor of a Binary Tree
2015-07-14 11:40
405 查看
题目:
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.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).”
_______3______ / \ ___5__ ___1__ / \ / \ 6 _2 0 8 / \ 7 4
For example, the lowest common ancestor (LCA) of nodes
5and
1is
3.
Another example is LCA of nodes
5and
4is
5,
since a node can be a descendant of itself according to the LCA definition.
思路:
参考:http://blog.csdn.net/u012243115/article/details/45367963 。代码:
/*** 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:
bool findPath(TreeNode *root , TreeNode *p , vector<TreeNode *> &tvec)
{
if(root == NULL)
return false;
tvec.push_back(root);
bool flag = false;
if(root == p)
{
flag = true;
return flag;
}
flag = findPath(root->left , p , tvec) || findPath(root->right , p , tvec);
if(!flag)
tvec.pop_back();
return flag;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
{
vector<TreeNode *> pvec , qvec;
findPath(root , p , pvec);
findPath(root , q , qvec);
vector<TreeNode *>::iterator iter1 , iter2 ;
TreeNode *result;
iter1 = pvec.begin();
iter2 = qvec.begin();
while(iter1 != pvec.end() && iter2 != qvec.end())
{
if(*iter1 == *iter2)
result = *iter1;
iter1++;
iter2++;
}
return result;
}
};
代码2:
/**
* 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)
return NULL;
//如果发现一个结点,就返回根结点
if(root == p || root == q)
return root;
TreeNode *leftLCA = lowestCommonAncestor(root->left , p , q);//如果leftLCA非空,说明有一个结点在左子树上
TreeNode *rightLCA = lowestCommonAncestor(root->right , p , q);//如果rightLCA非空,说明有一个结点在右子树上
// 如果都返回非空指针 Non-NULL, 则说明两个节点分别出现了在两个子树中,则当前节点肯定为LCA
if(leftLCA && rightLCA)
return root;
return leftLCA ? leftLCA : rightLCA;
}
};
相关文章推荐
- ViewHolder基类,带声音的SoundToast
- HDU 5273 Dylans loves sequence(线段树求逆序数对+离散化)
- curl返回常见错误码
- QTabWidget
- 《Spring技术内幕》学习笔记5——IoC容器的依赖注入
- IOS日期转为今天昨天形式
- C#减少图片文件大小和尺寸(转)
- [Linux]vbox 虚拟机添加新磁盘
- GRE写作必备句型
- 自己封装的java db可以和spring 进行整合
- [Linux]vbox 虚拟机添加新磁盘
- #18 4Sum
- 内存映射文件原理探索
- Unity3D第一个项目【控制模型移动】
- jQuery EasyUI API 中文文档 - DataGrid数据表格
- ASP.Net 获取当前时间,包含各种时间格式
- Android中Bitmap,byte[],Drawable相互转化
- ARRAYOFCONST 和 Format格式化数据
- java读取判断文件编码格式
- Android的Message Pool是个什么鬼——源码角度分析