File tree Expand file tree Collapse file tree 1 file changed +9
-3
lines changed
src/main/java/g0201_0300/s0236_lowest_common_ancestor_of_a_binary_tree Expand file tree Collapse file tree 1 file changed +9
-3
lines changed Original file line number Diff line number Diff line change 2
2
3
3
// #Medium #Top_100_Liked_Questions #Depth_First_Search #Tree #Binary_Tree
4
4
// #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 %)
6
6
7
7
import com_github_leetcode .TreeNode ;
8
8
17
17
*/
18
18
public class Solution {
19
19
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 ) {
21
24
return root ;
22
25
}
23
26
TreeNode left = lowestCommonAncestor (root .left , p , q );
24
27
TreeNode right = lowestCommonAncestor (root .right , p , q );
25
28
if (left != null && right != null ) {
26
29
return root ;
27
30
}
28
- return left != null ? left : right ;
31
+ if (left != null ) {
32
+ return left ;
33
+ }
34
+ return right ;
29
35
}
30
36
}
You can’t perform that action at this time.
0 commit comments