- Lowest Common Ancestor II
中文English
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.
The node has an extra attribute parent which point to the father of itself. The root’s parent is null.
Example
Example 1:
Input:
4
/
3 7
/
5 6
and 3,5
Output: 4
Explanation:LCA(3, 5) = 4
Example 2:
Input:
4
/
3 7
/
5 6
and 5,6
Output: 7
Explanation:LCA(5, 6) = 7
解法1:
A先往上拱,直到root,所有节点放入set。然后B再往上拱,看访问的节点是否在set中。
代码如下:
/**
* Definition of ParentTreeNode:
* class ParentTreeNode {
* public:
* int val;
* ParentTreeNode *parent, *left, *right;
* }
*/
class Solution {
public:
/*
* @param root: The root of the tree
* @param A: node in the tree
* @param B: node in the tree
* @return: The lowest common ancestor of A and B
*/
ParentTreeNode * lowestCommonAncestorII(ParentTreeNode * root, ParentTreeNode * A, ParentTreeNode * B) {
if (!root) return NULL;
if (root == A || root == B) return root;
unordered_set<ParentTreeNode *> s;
ParentTreeNode * tempA = A;
ParentTreeNode * tempB = B;
while(tempA) {
s.insert(tempA);
tempA = tempA->parent;
}
while (tempB) {
if (s.find(tempB) == s.end()) {
tempB = tempB->parent;
} else {
return tempB;
}
}
// return root;
}
};
解法2:A和B一起往上拱,所经过的节点都放入set。不管谁先遇到set中的元素就返回。
class Solution {
public:
/*
* @param root: The root of the tree
* @param A: node in the tree
* @param B: node in the tree
* @return: The lowest common ancestor of A and B
*/
ParentTreeNode * lowestCommonAncestorII(ParentTreeNode * root, ParentTreeNode * A, ParentTreeNode * B) {
if (!root) return NULL;
if (root == A || root == B) return root;
unordered_set<ParentTreeNode *> s;
ParentTreeNode * tempA = A;
ParentTreeNode * tempB = B;
while(tempA || tempB) {
if (tempA && s.find(tempA) != s.end()) return tempA;
s.insert(tempA);
if (tempB && s.find(tempB) != s.end()) return tempB;
s.insert(tempB);
tempA = tempA->parent;
tempB = tempB->parent;
}
// return root;
}
};
解法3:用Lowest Common Ancestor的分治法,不过没有用到parent,效率低。
博客围绕二叉树中最低公共祖先(LCA)问题展开,给定二叉树根节点及两个节点,节点有指向父节点的属性。通过具体示例展示问题,还给出三种解法,包括节点上拱结合集合判断、分治法等。
395

被折叠的 条评论
为什么被折叠?



