Skip to content

Commit dba2ab0

Browse files
refactor 1644
1 parent 65d9ce8 commit dba2ab0

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

src/main/java/com/fishercoder/solutions/_1644.java

+5-2
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,9 @@ private TreeNode dfs(TreeNode root, TreeNode p, TreeNode q) {
4848
}
4949

5050
public static class Solution2 {
51+
/**
52+
* This satisfies the follow-up question: Can you find the LCA traversing the tree, without checking nodes existence?
53+
*/
5154
int found = 0;
5255

5356
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
@@ -57,15 +60,15 @@ public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
5760

5861
private TreeNode lca(TreeNode root, TreeNode p, TreeNode q) {
5962
if (root == null) {
60-
return root;
63+
return null;
6164
}
6265
TreeNode left = lca(root.left, p, q);
6366
TreeNode right = lca(root.right, p, q);
6467
if (root == p || root == q) {
6568
found++;
6669
return root;
6770
}
68-
return left == null ? right : right == null ? left : root;
71+
return (left != null && right != null) ? root : left != null ? left : right;
6972
}
7073
}
7174
}

0 commit comments

Comments
 (0)