Skip to content

Commit 541c5ed

Browse files
author
Li Li
committed
add one more vary solution to 236
1 parent d04626d commit 541c5ed

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

top-interview-questions/236. Lowest Common Ancestor of a Binary Tree.cs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,36 @@ public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
77
if (left != null && right != null) return root;
88
return left == null ? right : left;
99
}
10+
}
11+
12+
// if there are parent for each node, the solution can be changed
13+
public ParentTreeNode lowestCommonAncestorII(ParentTreeNode root,
14+
ParentTreeNode A,
15+
ParentTreeNode B) {
16+
ArrayList<ParentTreeNode> pathA = getPath2Root(A);
17+
ArrayList<ParentTreeNode> pathB = getPath2Root(B);
18+
19+
int indexA = pathA.size() - 1;
20+
int indexB = pathB.size() - 1;
21+
22+
ParentTreeNode lowestAncestor = null;
23+
while (indexA >= 0 && indexB >= 0) {
24+
if (pathA.get(indexA) != pathB.get(indexB)) {
25+
break;
26+
}
27+
lowestAncestor = pathA.get(indexA);
28+
indexA--;
29+
indexB--;
30+
}
31+
32+
return lowestAncestor;
33+
}
34+
35+
private ArrayList<ParentTreeNode> getPath2Root(ParentTreeNode node) {
36+
ArrayList<ParentTreeNode> path = new ArrayList<>();
37+
while (node != null) {
38+
path.add(node);
39+
node = node.parent;
40+
}
41+
return path;
1042
}

0 commit comments

Comments
 (0)