File tree Expand file tree Collapse file tree 3 files changed +86
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 3 files changed +86
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def maxDepth (self , root : Optional [TreeNode ]) -> int :
3
+ """
4
+ Intuition:
5
+ ์ผ์ชฝ ์์๊ณผ ์ค๋ฅธ์ชฝ ์์์ ๋ํด depth๋ฅผ ์ฆ๊ฐ์ํค๋ฉฐ ์ฌ๊ทํ๊ณ ,
6
+ ๋ ์ค ํฐ ๊ฐ์ ๋ฐํํ๋ค.
7
+
8
+ Time Complexity:
9
+ O(N):
10
+ ๋ชจ๋ ๋
ธ๋์ ๋ํด ์ฌ๊ท์ ์ผ๋ก ํธ์ถํ๋ฏ๋ก O(N)์ด๋ค.
11
+
12
+ Space Complexity:
13
+ O(h):
14
+ ํธ๋ฆฌ์ ๋์ด h๋งํผ ์ฌ๊ท ํจ์๋ฅผ ํธ์ถํ๋ฏ๋ก,
15
+ ๊ณต๊ฐ ๋ณต์ก๋๋ O(h)์ด๋ค.
16
+ """
17
+
18
+ def get_depth (node , depth ):
19
+ if not node :
20
+ return depth
21
+
22
+ left = get_depth (node .left , depth + 1 )
23
+ right = get_depth (node .right , depth + 1 )
24
+ return max (left , right )
25
+
26
+ answer = get_depth (root , 0 )
27
+ return answer
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def merge (self , intervals : List [List [int ]]) -> List [List [int ]]:
3
+ """
4
+ Intuition:
5
+ ์ ๋ ฌ๋ intervals์ ์ํํ๋ฉด์ ์ด์ ์ ์ธํฐ๋ฒ๊ณผ ํ์ฌ ์ธํฐ๋ฒ์ด
6
+ ๊ฒน์น๋ค๋ฉด, ์ด๋ฅผ ๊ฐฑ์ ํด์ค๋ค.
7
+ ๊ฒน์น์ง ์๋๋ค๋ฉด, ์๋ก์ด ์ธํฐ๋ฒ์ ์ถ๊ฐํ๋ค.
8
+
9
+ Time Complexity:
10
+ O(N log N):
11
+ ์ต์ด์ ์ ๋ ฌ์ ํ๋ฏ๋ก, O(N log N)์ด๋ค.
12
+ ์ดํ ํ๋ฒ ์ค์บ์ ํ๋ฏ๋ก O(N)์ด๋ค.
13
+ ๋ฐ๋ผ์ ์๊ฐ ๋ณต์ก๋๋ O(N log N)์ด๋ค.
14
+
15
+ Space Complexity:
16
+ O(N):
17
+ answer์ N๊ฐ์ ๊ฐ์ ์ ์ฅํ๋ฏ๋ก O(N)์ด๋ค.
18
+ """
19
+ sorted_intervals = sorted (intervals )
20
+
21
+ answer = [sorted_intervals [0 ]]
22
+ for start , end in sorted_intervals [1 :]:
23
+ prev_start , prev_end = answer [- 1 ]
24
+ if prev_end >= start :
25
+ answer [- 1 ][1 ] = max (prev_end , end )
26
+ else :
27
+ answer .append ([start , end ])
28
+ return answer
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def reorderList (self , head : Optional [ListNode ]) -> None :
3
+ """
4
+ Intuition:
5
+ nodes ๋ฆฌ์คํธ์ ๋ชจ๋ ๋
ธ๋๋ฅผ ์ ์ฅํ๋ค.
6
+ ํ์ฌ ๋
ธ๋๊ฐ -i - 1๋ฒ์งธ ๋
ธ๋์ผ ๋,
7
+ ํ์ฌ ๋
ธ๋์ next๋ head์ next๋ก ์ค์ ํ๊ณ ,
8
+ head์ next๋ ํ์ฌ ๋
ธ๋๋ก ์ค์ ํ๋ค.
9
+ ์ดํ ๋ง์ง๋ง์ ์ค๊ฐ์ ์๋ ๋
ธ๋๋ฅผ None์ผ๋ก ์ค์ ํ๋ค.
10
+
11
+ Time Complexity:
12
+ O(N):
13
+ ๋ชจ๋ ๋
ธ๋๋ฅผ ์ํํ๋ฏ๋ก O(N)์ด๋ค.
14
+
15
+ Space Complexity:
16
+ O(N):
17
+ ๋ชจ๋ ๋
ธ๋๋ฅผ nodes ๋ฆฌ์คํธ์ ์ ์ฅํ๋ฏ๋ก O(N)์ด๋ค.
18
+ """
19
+ nodes = []
20
+ node = head
21
+ while node :
22
+ nodes .append (node )
23
+ node = node .next
24
+
25
+ for i in range ((len (nodes ) - 1 ) // 2 ):
26
+ cur = nodes [- i - 1 ]
27
+ cur .next = head .next
28
+ head .next = cur
29
+ head = cur .next
30
+
31
+ nodes [len (nodes ) // 2 ].next = None
You canโt perform that action at this time.
0 commit comments