/**
* Definition of ParentTreeNode:
*
* class ParentTreeNode {
* public ParentTreeNode parent, left, right;
* }
*/
/*
与1不同的是多了一个子向父的指针 先找其中一个node到root的所有父节点 然后用另外一个遍历 找到相同的节点为止;
*/
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) {
// write your code here
if(root == null || root == A || root == B) return root;
ArrayList<ParentTreeNode> nodeList = new ArrayList<>();
while(B != root) {
nodeList.add(B);
B = B.parent;
}
while(A != root) {
if(nodeList.contains(A)) return A;
A = A.parent;
}
return root;
}
}