Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitdba2ab0

Browse files
refactor 1644
1 parent65d9ce8 commitdba2ab0

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
publicstaticclassSolution2 {
51+
/**
52+
* This satisfies the follow-up question: Can you find the LCA traversing the tree, without checking nodes existence?
53+
*/
5154
intfound =0;
5255

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

5861
privateTreeNodelca(TreeNoderoot,TreeNodep,TreeNodeq) {
5962
if (root ==null) {
60-
returnroot;
63+
returnnull;
6164
}
6265
TreeNodeleft =lca(root.left,p,q);
6366
TreeNoderight =lca(root.right,p,q);
6467
if (root ==p ||root ==q) {
6568
found++;
6669
returnroot;
6770
}
68-
returnleft==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)

[8]ページ先頭

©2009-2025 Movatter.jp