您的位置:首页 > 其它

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 
5
 and 
1
 is 
3
.
Another example is LCA of nodes 
5
 and 
4
 is 
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: