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.
找出二叉树中的两个节点p和q的共同的最低层的祖先,这里定义的祖先可以是自己本身。用递归的方法,计算当前结点及其左右子树中含p和q的个数,如果有两个,且答案还没出现,说明当前结点就是p和q的共同的最低层的祖先,标记为答案。其后的搜索就可以直接跳过。
代码:
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
lca(root, p, q);
return res;
}
private:
TreeNode* res = NULL;
int lca(TreeNode* root, TreeNode* p, TreeNode* q)
{
if(!root || res) return 0;
int ret = (root == p ? 1 : 0) + (root == q ? 1 : 0);
ret += lca(root->left, p, q);
ret += lca(root->right, p, q);
if(ret >= 2 && !res) res = root;
return ret;
}
};