Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the two nodes.
The lowest common ancestor is the node with largest depth which is the ancestor of both nodes.
Returnnullif LCA does not exist.
Notice
node A or node B may not exist in tree.
Have you met this question in a real interview?
Yes
Example
For the following binary tree:
4
/ \
3 7
/ \
5 6
LCA(3, 5) =4
LCA(5, 6) =7
LCA(6, 7) =7
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of the binary tree.
* @param A and B: two nodes
* @return: Return the LCA of the two nodes.
*/
TreeNode *lowestCommonAncestor3(TreeNode* root, TreeNode* A, TreeNode* B) {
// write your code here
vector<TreeNode*> pathA;
vector<TreeNode*> pathB;
if (!dfs(root, pathA, A)) {
return NULL;
}
if (!dfs(root, pathB, B)) {
return NULL;
}
return getAncestor(pathA, pathB);
}
private:
bool dfs(TreeNode* root, vector<TreeNode*> &path, TreeNode *node) {
if (root == NULL) {
return false;
}
if (root == node) {
path.push_back(root);
return true;
}
path.push_back(root);
if (dfs(root->left, path, node)) {
return true;
}
if (dfs(root->right, path, node)) {
return true;
}
path.pop_back();
return false;
}
TreeNode* getAncestor(vector<TreeNode*> &left, vector<TreeNode*> &right) {
TreeNode* pre = left[0];
int i = 1;
while (i < left.size() && i < right.size()) {
if (left[i] != right[i]) {
break;
}
pre = left[i];
++i;
}
return pre;
}
};