Skip to content

Commit cb9c5f2

Browse files
committed
Update Solution.java
1 parent 829e797 commit cb9c5f2

File tree

1 file changed

+9
-3
lines changed
  • src/main/java/g0201_0300/s0236_lowest_common_ancestor_of_a_binary_tree

1 file changed

+9
-3
lines changed

src/main/java/g0201_0300/s0236_lowest_common_ancestor_of_a_binary_tree/Solution.java

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
// #Medium #Top_100_Liked_Questions #Depth_First_Search #Tree #Binary_Tree
44
// #Data_Structure_II_Day_18_Tree #Udemy_Tree_Stack_Queue #Big_O_Time_O(n)_Space_O(n)
5-
// #2024_11_16_Time_6_ms_(100.00%)_Space_44.8_MB_(36.66%)
5+
// #2024_11_16_Time_6_ms_(100.00%)_Space_44_MB_(98.99%)
66

77
import com_github_leetcode.TreeNode;
88

@@ -17,14 +17,20 @@
1717
*/
1818
public class Solution {
1919
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
20-
if (root == null || root == p || root == q) {
20+
if (root == null) {
21+
return null;
22+
}
23+
if (root.val == p.val || root.val == q.val) {
2124
return root;
2225
}
2326
TreeNode left = lowestCommonAncestor(root.left, p, q);
2427
TreeNode right = lowestCommonAncestor(root.right, p, q);
2528
if (left != null && right != null) {
2629
return root;
2730
}
28-
return left != null ? left : right;
31+
if (left != null) {
32+
return left;
33+
}
34+
return right;
2935
}
3036
}

0 commit comments

Comments
 (0)