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},3,5
Output:4
Explanation:
4
/ \
3 7
/ \
5 6
LCA(3, 5) = 4
Example 2:
Input:{4,3,7,#,#,5,6},5,6
Output:7
Explanation:
4
/ \
3 7
/ \
5 6
LCA(5, 6) = 7
思路:有parent指针,就用hashset解决,从node A一路走上去,收集起来,然后从node B再往上走,如果遇见相同的则返回,否则最后返回root
/**
* Definition of ParentTreeNode:
*
* class ParentTreeNode {
* public ParentTreeNode parent, left, right;
* }
*/
public class Solution {
/*
* @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
*/
public ParentTreeNode lowestCommonAncestorII(ParentTreeNode root, ParentTreeNode A, ParentTreeNode B) {
if(root == null) return null;
HashSet<ParentTreeNode> hashset = new HashSet<ParentTreeNode>();
ParentTreeNode node = A;
while(node != root) {
hashset.add(node);
node = node.parent;
}
hashset.add(root);
node = B;
while(node != root) {
if(hashset.contains(node)){
return node;
}
node = node.parent;
}
return root;
}
}
思路2:收集两条路线,然后从上往下走,遇见第一个不相等的index break,return break之前的node
/**
* Definition of ParentTreeNode:
*
* class ParentTreeNode {
* public ParentTreeNode parent, left, right;
* }
*/
public class Solution {
/*
* @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
*/
public ParentTreeNode lowestCommonAncestorII(ParentTreeNode root, ParentTreeNode A, ParentTreeNode B) {
if(root == null) {
return null;
}
List<ParentTreeNode> pathA = findPath(root, A);
List<ParentTreeNode> pathB = findPath(root, B);
return findLowestCommon(pathA, pathB);
}
private ParentTreeNode findLowestCommon(List<ParentTreeNode> pathA, List<ParentTreeNode> pathB) {
int lenA = pathA.size();
int lenB = pathB.size();
int len = Math.min(lenA, lenB);
ParentTreeNode res = pathA.get(0);
for(int i = 0; i < len; i++) {
if(pathA.get(i) == pathB.get(i)){
res = pathA.get(i);
}
}
return res;
}
private List<ParentTreeNode> findPath(ParentTreeNode root, ParentTreeNode A) {
List<ParentTreeNode> list = new ArrayList<ParentTreeNode>();
ParentTreeNode node = A;
while(node != root) {
list.add(0,node);
node = node.parent;
}
list.add(0,root);
return list;
}
}