在这里插入图片描述给一棵二叉树和二叉树中的两个节点,找到这两个节点的最近公共祖先LCA。
两个节点的最近公共祖先,是指两个节点的所有父亲节点中(包括这两个节点),离这两个节点最近的公共的节 点。
每个节点除了左右儿子指针以外,还包含一个父亲指针parent,指向自己的父亲。
实现:
/**
* 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 || root == A || root == B)
return root;
ArrayList<ParentTreeNode> parentA = getParents(A);
ArrayList<ParentTreeNode> parentB = getParents(B);
int aSize = parentA.size() - 1;
int bSize = parentB.size() - 1;
ParentTreeNode result = root;
while (aSize >= 0 && bSize >= 0) {
if (parentA.get(aSize) != parentB.get(bSize)) {
break;
}
result = parentA.get(aSize);
aSize--;
bSize--;
}
// write your code here
return result;
}
private ArrayList<ParentTreeNode> getParents(ParentTreeNode node) {
ArrayList<ParentTreeNode> list = new ArrayList<ParentTreeNode>();
while (node != null) {
list.add(node);
node = node.parent;
}
return list;
}
}
网友评论