Skip to content

Commit 433c62a

Browse files
committed
Updated Lowest Common Ancestor of a Binary Tree.java
1 parent 2a5879f commit 433c62a

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

Medium/Lowest Common Ancestor of a Binary Tree.java

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,21 @@
88
* }
99
*/
1010
class Solution {
11-
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
12-
if (root == null || root == p || root == q) {
13-
return root;
11+
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
12+
if (root == null) {
13+
return null;
14+
}
15+
if (root == p || root == q) {
16+
return root;
17+
}
18+
TreeNode left = lowestCommonAncestor(root.left, p, q);
19+
TreeNode right = lowestCommonAncestor(root.right, p, q);
20+
if (left != null && right != null) {
21+
return root;
22+
}
23+
if (left != null || right != null) {
24+
return left != null ? left : right;
25+
}
26+
return null;
1427
}
15-
TreeNode leftRoot = lowestCommonAncestor(root.left, p, q);
16-
TreeNode rightRoot = lowestCommonAncestor(root.right, p, q);
17-
if (leftRoot != null && rightRoot != null) {
18-
return root;
19-
}
20-
return leftRoot != null ? leftRoot : rightRoot;
21-
}
2228
}

0 commit comments

Comments
 (0)