description:
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
For the following binary tree:
4
/ \
3 7
/ \
5 6
这个题目中带有parent point 因此做起来要比较容易一些。
/**
* Definition of ParentTreeNode:
*
* class ParentTreeNode {
* public ParentTreeNode parent, left, right;
* }
*/
public class Solution {
/**
* @param root: The root of the tree
* @param A, B: Two node in the tree
* @return: The lowest common ancestor of A and B
*/
public ParentTreeNode lowestCommonAncestorII(ParentTreeNode root,
ParentTreeNode A,
ParentTreeNode B) {
// Write your code here
List<ParentTreeNode> listA = findAncestor(A);
List<ParentTreeNode> listB = findAncestor(B);
int lenA = listA.size() - 1;
int lenB = listB.size() - 1;
ParentTreeNode result = null;
while (lenA >= 0 && lenB >= 0) {
if (listA.get(lenA) != listB.get(lenB)) {
break;
}
result = listA.get(lenA);
lenA--;
lenB--;
}
return result;
}
public List<ParentTreeNode> findAncestor(ParentTreeNode root) {
List<ParentTreeNode> list = new ArrayList<>();
while (root != null) {
list.add(root);
root = root.parent;
}
return list;
}
}