-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add 1644_Lowest_Common_Ancestor_of_a_Binary_Tree_II.java
- Loading branch information
1 parent
b021672
commit 22fd2a0
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
40 changes: 40 additions & 0 deletions
40
Tree Depth First Search/1644_Lowest_Common_Ancestor_of_a_Binary_Tree_II.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
class Solution { | ||
private boolean pFound = false, qFound = false; | ||
|
||
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { | ||
TreeNode result = helper(root, p, q); | ||
|
||
if (pFound && qFound && result != null) { | ||
return result; | ||
} | ||
return null; | ||
} | ||
|
||
private TreeNode helper(TreeNode root, TreeNode p, TreeNode q) { | ||
if (root == null) { | ||
return null; | ||
} | ||
|
||
TreeNode left = helper(root.left, p, q); | ||
TreeNode right = helper(root.right, p, q); | ||
|
||
if (root == p) { | ||
pFound = true; | ||
return root; | ||
} | ||
|
||
if (root == q) { | ||
qFound = true; | ||
return root; | ||
} | ||
|
||
if (left == null) { | ||
return right; | ||
} | ||
if (right == null) { | ||
return left; | ||
} | ||
|
||
return root; | ||
} | ||
} |