File tree Expand file tree Collapse file tree 2 files changed +59
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 2 files changed +59
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Time complexity O(n)
3
+ """
4
+ from collections import deque
5
+
6
+ class Solution :
7
+ def maxDepth (self , root : Optional [TreeNode ]) -> int :
8
+ if not root :
9
+ return 0
10
+
11
+ max_depth = 0
12
+
13
+ # bfs
14
+ q = deque ([[root , 1 ]])
15
+ while (q ):
16
+ node , depth = q .pop ()
17
+ if max_depth < depth :
18
+ max_depth = depth
19
+ if node .left :
20
+ q .append ([node .left , depth + 1 ])
21
+ if node .right :
22
+ q .append ([node .right , depth + 1 ])
23
+
24
+ return max_depth
Original file line number Diff line number Diff line change
1
+ """
2
+ Time complexity O(n+m)
3
+ """
4
+
5
+ class Solution :
6
+ def mergeTwoLists (self , list1 : Optional [ListNode ], list2 : Optional [ListNode ]) -> Optional [ListNode ]:
7
+ if not (list1 or list2 ):
8
+ return list1 or list2 # if empty list
9
+
10
+ nums = []
11
+ while (list1 or list2 ):
12
+ if not list1 :
13
+ val = list2 .val
14
+ list2 = list2 .next
15
+ elif not list2 :
16
+ val = list1 .val
17
+ list1 = list1 .next
18
+ else :
19
+ if list1 .val <= list2 .val :
20
+ val = list1 .val
21
+ list1 = list1 .next
22
+ else :
23
+ val = list2 .val
24
+ list2 = list2 .next
25
+ nums .append (val )
26
+
27
+ head = ListNode (nums [0 ])
28
+ node = head
29
+ if len (nums ) == 1 :
30
+ return head
31
+ for n in nums [1 :]:
32
+ tmp = ListNode (n )
33
+ node .next = tmp
34
+ node = tmp
35
+ return head
You can’t perform that action at this time.
0 commit comments