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.
思路:首先深度遍历二叉树,找到从根节点开始到目标节点的路径。两个节点的最近公共祖先就是两个路径的交点处。
例: 节点5和8的路径分别为 3->5和3->1->8 两条链相交于3
节点6和4的路径分别为3->5->6和3->5->2->4相交于5
代码:
/**
* 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:
vector<TreeNode *> path(TreeNode* root, TreeNode *p)
{
if (root == nullptr) return vector<TreeNode *>();
//深度遍历到底都没有找到目标节点,说明该路径不存在目标节点
else
{
if (root == p)
{
//某条路径上找到目标节点,不用再继续深入遍历了
vector<TreeNode *> tempPath;
tempPath.push_back(p);
return tempPath;
}
else
{
vector<TreeNode *> l = path(root->left, p);
//将该节点插入到包含目标节点的路径上,左子树或右子树,为空则不包含目标节点
if (!l.empty())
{
l.push_back(root);
return l;
}
else
{
vector<TreeNode *> r = path(root->right, p);
if (r.empty()) return r;
r.push_back(root);
return r;
}
}
}
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
//深度遍历得到两条路径
vector<TreeNode *> pathp = path(root,p);
vector<TreeNode *> pathq = path(root,q);
vector<TreeNode *>::iterator longer,shortter;
//寻找着两条链的公共节点
longer = pathp.size() >= pathq.size() ? pathp.begin():pathq.begin();
shortter = pathp.size() < pathq.size() ? pathp.begin():pathq.begin();
int sub = abs((int)pathp.size() - (int)pathq.size());
for(;sub>0;--sub)
++longer;
while((*longer) != (*shortter))
++longer,++shortter;
return *longer;
}
};
这条语句必须进行类型转换,因为vector的size函数返回值为unsigned int当pathp的长度小于pathq的长度会得不到正确的结果
int sub = abs((int)pathp.size() - (int)pathq.size());