File tree 2 files changed +83
-0
lines changed
maximum-depth-of-binary-tree
2 files changed +83
-0
lines changed Original file line number Diff line number Diff line change
1
+ import collections
2
+
3
+ # Definition for a binary tree node.
4
+ class TreeNode (object ):
5
+ def __init__ (self , val = 0 , left = None , right = None ):
6
+ self .val = val
7
+ self .left = left
8
+ self .right = right
9
+
10
+ class Solution (object ):
11
+ def maxDepth (self , root ):
12
+ """
13
+ :type root: Optional[TreeNode]
14
+ :rtype: int
15
+ ์ฃผ์ด์ง ์ด์ง ํธ๋ฆฌ์ ์ต๋ ๊น์ด(๋ฃจํ์์ ๋ฆฌํ๊น์ง์ ๊ฐ์ฅ ๊ธด ๊ฒฝ๋ก์ ๋
ธ๋ ์)๋ฅผ ๊ตฌํ๋ ๋ฌธ์
16
+ BFS๋ก ํ๋ฅผ ์ฌ์ฉํด ์ต๋ ๊น์ด๋ฅผ ๊ตฌํจ.
17
+ Time complexity: O(n), n๊ฐ์ ๋
ธ๋๋ฅผ ํ ๋ฒ์ฉ ๋ฐฉ๋ฌธ.
18
+ Space complexity: O(w), w๋ ํธ๋ฆฌ์ ์ต๋ ๋๋น (n/2).
19
+ """
20
+ if root is None :
21
+ return 0
22
+
23
+ depth = 0
24
+
25
+ queue = collections .deque ([root ])
26
+
27
+ while queue :
28
+ depth += 1
29
+ level_size = len (queue )
30
+ for _ in range (level_size ):
31
+ node = queue .popleft ()
32
+ if node .left is not None :
33
+ queue .append (node .left )
34
+ if node .right is not None :
35
+ queue .append (node .right )
36
+ return depth
Original file line number Diff line number Diff line change
1
+ # Definition for singly-linked list.
2
+ class ListNode (object ):
3
+ def __init__ (self , val = 0 , next = None ):
4
+ self .val = val
5
+ self .next = next
6
+
7
+ class Solution (object ):
8
+ def mergeTwoLists (self , list1 , list2 ):
9
+ """
10
+ :type list1: Optional[ListNode]
11
+ :type list2: Optional[ListNode]
12
+ :rtype: Optional[ListNode]
13
+ - TC: O(m+n)
14
+ - SC: O(1)
15
+ """
16
+
17
+ # ์ฃ์ง ์ผ์ด์ค
18
+ # ๋ ๋ฆฌ์คํธ ์ค ํ๋๋ผ๋ ๋น์ด ์๋ ๊ฒฝ์ฐ,
19
+ # ๋๋จธ์ง ๋ฆฌ์คํธ ๋ฐ๋ก ๋ฐํ
20
+ if not list1 :
21
+ return list2
22
+ if not list2 :
23
+ return list1
24
+
25
+ # ๋๋ฏธ ํค๋ ๋
ธ๋
26
+ # ๊ฒฐ๊ณผ ๋ฆฌ์คํธ ์์์ ์ญํ ์ ํ ๊ฐ์ง ๋
ธ๋ ์์ฑ
27
+ dummy = ListNode ()
28
+ current = dummy # current๋ ํ์ฌ๊น์ง ๋ง๋ ๋ฆฌ์คํธ์ ๋ง์ง๋ง ๋
ธ๋
29
+
30
+ # ๋ ๋ฆฌ์คํธ ๋ชจ๋ ๋
ธ๋๊ฐ ๋จ์ ์์ ๋๊น์ง ๋ฐ๋ณต
31
+ while list1 and list2 :
32
+ if list1 .val <= list2 .val :
33
+ current .next = list1
34
+ list1 = list1 .next
35
+ else :
36
+ current .next = list2
37
+ list2 = list2 .next
38
+ current = current .next
39
+
40
+ # ๋จ์ ๋
ธ๋๋ค ์ด์ด ๋ถ์ด๊ธฐ
41
+ # ์์ง ๋
ธ๋๊ฐ ๋จ์ ์๋ ๋ฆฌ์คํธ๊ฐ ์์ผ๋ฉด ํต์งธ๋ก ๋ถ์ด๊ธฐ
42
+ if list1 :
43
+ current .next = list1
44
+ elif list2 :
45
+ current .next = list2
46
+
47
+ return dummy .next
You canโt perform that action at this time.
0 commit comments