Skip to content

Commit

Permalink
Add 1644_Lowest_Common_Ancestor_of_a_Binary_Tree_II.java
Browse files Browse the repository at this point in the history
  • Loading branch information
seanprashad committed Mar 25, 2021
1 parent b021672 commit 22fd2a0
Showing 1 changed file with 40 additions and 0 deletions.
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;
}
}

0 comments on commit 22fd2a0

Please sign in to comment.