Skip to content

Commit 22fd2a0

Browse files
committed
Add 1644_Lowest_Common_Ancestor_of_a_Binary_Tree_II.java
1 parent b021672 commit 22fd2a0

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
private boolean pFound = false, qFound = false;
3+
4+
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
5+
TreeNode result = helper(root, p, q);
6+
7+
if (pFound && qFound && result != null) {
8+
return result;
9+
}
10+
return null;
11+
}
12+
13+
private TreeNode helper(TreeNode root, TreeNode p, TreeNode q) {
14+
if (root == null) {
15+
return null;
16+
}
17+
18+
TreeNode left = helper(root.left, p, q);
19+
TreeNode right = helper(root.right, p, q);
20+
21+
if (root == p) {
22+
pFound = true;
23+
return root;
24+
}
25+
26+
if (root == q) {
27+
qFound = true;
28+
return root;
29+
}
30+
31+
if (left == null) {
32+
return right;
33+
}
34+
if (right == null) {
35+
return left;
36+
}
37+
38+
return root;
39+
}
40+
}

0 commit comments

Comments
 (0)