# int32bit / leetcode

Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
..
Failed to load latest commit information.
tree.cpp

## Lowest Common Ancestor of a Binary Tree

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.

## Solution

• 若两个节点分别在左右子树，则当前节点就是最低公共祖先节点
• 若两个节点都在左子树，则最低公共祖先节点在左子树
• 若两个节点都在右子树，则最低公共祖先节点在右子树 简单的方法是:
```TreeNode *LCA(TreeNode *root, TreeNode *p, TreeNode *q)
{
bool left = findAny(root->left, p, q);
bool right = findAny(root->right, p, q);
if (left && right)
return root;
if (left)
return LCA(root->left, p, q);
if (right)
return LCA(root->right, p, q);
return nullptr;
}```

```TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)
{
if (root == nullptr)
return nullptr;
if (root == p || root == q)
return root;
TreeNode *left = lowestCommonAncestor(root->left, p, q);
TreeNode *right = lowestCommonAncestor(root->right, p, q);
if (left && right)
return root;
return left ? left:right;
}```

```bool getPath(TreeNode *root, TreeNode *p, list<TreeNode *> &path) {
if (root == nullptr)
return p == nullptr;
path.push_back(root);
if (root == p)
return true;
if (getPath(root->left, p, path) || getPath(root->right, p, path))
return true;
else {
path.pop_back();
return false;
}
}```

```TreeNode *findCommonNode(const list<TreeNode *> &l1, const list<TreeNode *> &l2) {
int n = l1.size();
int m = l2.size();
auto i = begin(l1), j = begin(l2);
TreeNode *last = nullptr;
while (i != end(l1) && j != end(l2)) {
if (*i == *j) {
last = *i;
}
i++, j++;
}
return last;
}```

```TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)
{
if (root == nullptr)
return nullptr;
list<TreeNode *> l1, l2;
getPath(root, p, l1);
getPath(root, q, l2);
/*
for_each(begin(l1), end(l1), [](TreeNode *t){cout << t->val << ' ';});
cout << endl;
for_each(begin(l2), end(l2), [](TreeNode *t){cout << t->val << ' ';});
cout << endl;
*/
return findCommonNode(l1, l2);
}```

## 相关题目

You can’t perform that action at this time.