Skip to content

Commit fc38c9b

Browse files
add a solution for 1644
1 parent 059d9a9 commit fc38c9b

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

Diff for: src/main/java/com/fishercoder/solutions/_1644.java

+34-1
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ private TreeNode dfs(TreeNode root, TreeNode p, TreeNode q) {
4949

5050
public static class Solution2 {
5151
/**
52-
* This satisfies the follow-up question: Can you find the LCA traversing the tree, without checking nodes existence?
52+
* This still checks nodes existence.
5353
*/
5454
int found = 0;
5555

@@ -71,4 +71,37 @@ private TreeNode lca(TreeNode root, TreeNode p, TreeNode q) {
7171
return (left != null && right != null) ? root : left != null ? left : right;
7272
}
7373
}
74+
75+
public static class Solution3 {
76+
/**
77+
* Credit: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-ii/solutions/944963/beat-96-recursion-without-count-easy-understanding/
78+
*/
79+
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
80+
if (root == null || p == null || q == null) {
81+
return null;
82+
}
83+
TreeNode result = findLCA(root, p, q);
84+
if (result == p) {
85+
//if p equals result, we'll check the existence of q in the subtree of p
86+
return findLCA(p, q, q) != null ? result : null;
87+
} else if (result == q) {
88+
//if q equals result, we'll check the existence of p in the subtree of q
89+
return findLCA(q, p, p) != null ? result : null;
90+
}
91+
//otherwise, it's this case: (p != result && q != result) || result == null
92+
return result;
93+
}
94+
95+
private TreeNode findLCA(TreeNode root, TreeNode p, TreeNode q) {
96+
if (root == null || p == root || q == root) {
97+
return root;
98+
}
99+
TreeNode left = findLCA(root.left, p, q);
100+
TreeNode right = findLCA(root.right, p, q);
101+
if (left != null && right != null) {
102+
return root;
103+
}
104+
return left != null ? left : right;
105+
}
106+
}
74107
}

0 commit comments

Comments
 (0)