File tree Expand file tree Collapse file tree 2 files changed +81
-0
lines changed
binary-tree-level-order-traversal Expand file tree Collapse file tree 2 files changed +81
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ Solution: BFS
3+ Time: O(n)
4+ Space: O(n)
5+ """
6+
7+ class Solution :
8+ def levelOrder (self , root : Optional [TreeNode ]) -> List [List [int ]]:
9+ if not root : return []
10+
11+ q = deque ([root ])
12+ result = []
13+ while q :
14+ level = []
15+ for i in range (len (q )):
16+ node = q .popleft ()
17+ level .append (node .val )
18+ if node .left : q .append (node .left )
19+ if node .right : q .append (node .right )
20+ result .append (level )
21+
22+ return result
Original file line number Diff line number Diff line change 1+
2+ """
3+ Solution:
4+ 1) bin() ๋ฉ์๋๋ก binary ๋ง๋ค์ด์ฃผ๊ณ
5+ 2) 1 ์ ๊ฐฏ์๋ฅผ ์ธ์ด์ค๋ค.
6+ Time: O(n^2)
7+ Space: O(1)
8+ """
9+
10+ class Solution :
11+ def countBits (self , n : int ) -> List [int ]:
12+ result = [0 for i in range (n + 1 )]
13+
14+ for i in range (n + 1 ):
15+ b = bin (i )
16+ count = 0
17+ for char in b :
18+ if char == '1' :
19+ count += 1
20+ result [i ] = count
21+
22+ return result
23+
24+ """
25+ Solution:
26+ 1) 2๋ก ๋๋ ๋๋จธ์ง๊ฐ 1bit ์ด๋ผ๋ ์ฑ์ง์ ์ด์ฉํด์ count
27+ Time: O(n logn)
28+ Space: O(1)
29+ """
30+
31+ class Solution :
32+ def countBits (self , n : int ) -> List [int ]:
33+ def count (num ):
34+ count = 0
35+ while num > 0 :
36+ count += num % 2
37+ num = num // 2
38+ return count
39+
40+ return [count (i ) for i in range (n + 1 )]
41+
42+ """
43+ Solution:
44+ 1) LSB ๊ฐ 0 1 0 1 ๋ฐ๋ณต๋๋ฏ๋ก num % 2 ๋ฅผ ์ฌ์ฉํ๋ค.
45+ 2) ๋๋จธ์ง ๋น์ LSB๋ฅผ ์ ์ธํ ๊ฐ์ด๋ฏ๋ก num // 2 ๋ฅผ ์ฌ์ฉํ๋ค.
46+ Time: O(n)
47+ Space: O(1)
48+ """
49+
50+ class Solution :
51+
52+ def countBits (self , n : int ) -> List [int ]:
53+ dp = [0 for i in range (n + 1 )]
54+
55+ for i in range (1 , n + 1 ):
56+ LSB = i % 2
57+ dp [i ] = dp [i // 2 ] + LSB
58+
59+ return dp
You canโt perform that action at this time.
0 commit comments