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

Lines changed: 5 additions & 2 deletions
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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy