File tree Expand file tree Collapse file tree 2 files changed +14
-23
lines changed Expand file tree Collapse file tree 2 files changed +14
-23
lines changed Original file line number Diff line number Diff line change 1
1
- https://leetcode.com/problems/invert-binary-tree/
2
2
- time complexity : O(n)
3
- - space complexity : O(log n)
3
+ - space complexity : O(h), h = tree height
4
4
- https://algorithm.jonghoonpark.com/2024/03/31/leetcode-226
5
5
6
6
``` java
Original file line number Diff line number Diff line change 6
6
``` java
7
7
class Solution {
8
8
public ListNode mergeTwoLists (ListNode list1 , ListNode list2 ) {
9
- ListNode head = null ;
10
- ListNode tail = null ;
9
+ ListNode head = new ListNode ( 0 ) ;
10
+ ListNode tail = head ;
11
11
12
- while (! (list1 == null && list2 == null )) {
13
- ListNode selected;
14
- if (list1 == null ) {
15
- selected = list2;
16
- list2 = list2. next;
17
- } else if (list2 == null ) {
18
- selected = list1;
19
- list1 = list1. next;
20
- } else if (list1. val < list2. val) {
21
- selected = list1;
12
+ while (list1 != null && list2 != null ) {
13
+ if (list1. val < list2. val) {
14
+ tail. next = list1;
22
15
list1 = list1. next;
23
16
} else {
24
- selected = list2;
17
+ tail . next = list2;
25
18
list2 = list2. next;
26
19
}
20
+ tail = tail. next;
21
+ }
27
22
28
- ListNode newNode = new ListNode (selected. val);
29
- if (head == null ) {
30
- head = newNode;
31
- } else {
32
- tail. next = newNode;
33
- }
34
-
35
- tail = newNode;
23
+ if (list1 != null ) {
24
+ tail. next = list1;
25
+ } else {
26
+ tail. next = list2;
36
27
}
37
28
38
- return head;
29
+ return head. next ;
39
30
}
40
31
}
41
32
```
You can’t perform that action at this time.
0 commit comments