-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathall_possible_full_binary_trees.py
More file actions
59 lines (46 loc) ยท 1.9 KB
/
all_possible_full_binary_trees.py
File metadata and controls
59 lines (46 loc) ยท 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# 894. All Possible Full Binary Trees
# https://leetcode.com/problems/all-possible-full-binary-trees/
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
"""
์ฃผ์ด์ง N๊ฐ์ ์ซ์๋งํผ ๋
ธ๋๋ฅผ ๊ฐ์ง๊ณ ์์ ๋ full binary tree node ๋ฅผ ์์ฑํ๋ ๋ฌธ์ ๋ค.
full binary tree node๋ ์์ ๋
ธ๋๊ฐ ์๊ฑฐ๋ ์์ ๋
ธ๋๊ฐ ๋์ด๋ค.
"""
def allPossibleFBT(self, N):
# ๋
ธ๋๊ฐ 1๊ฐ ์ผ ๋ ์์ฑ
if N == 1:
return [TreeNode(0)]
N -= 1
ans = []
# ๋ถ๋ชจ ๋
ธ๋ 1๊ฐ๋ฅผ ์ ์ธํ ์์ ๋
ธ๋ 2๊ฐ์ฉ ๋ง๋ค์ด์ฃผ๊ธฐ ์ํด์ i๋ 1๋ถํฐ N ๊น์ง 2 ์ฉ ์ฆ๊ฐํ๋ค.
# i ๋ ์์ฑ ํ ํธ๋ฆฌ ๋
ธ๋ ๊ฐ์๊ฐ ๋๋ค.
# ์ข์ธก ๋
ธ๋๊ฐ i ๊ฐ ์์ฑ๋๋ฉด ์ฐ์ธก ๋
ธ๋๋ N-i ๊ฐ ์์ฑ๋์ด์ผ ํ๋ค.
for i in range(1, N, 2):
# ์ข์ธก ๋
ธ๋ ์์ฑ
left = self.allPossibleFBT(i)
# ์ฐ์ธก ๋
ธ๋ ์์ฑ
right = self.allPossibleFBT(N - i)
for nl in left:
for nr in right:
# ๋ถ๋ชจ ๋
ธ๋
node = TreeNode(0)
# ์ข์ธก์์ ๋์จ ๋
ธ๋ ๋ฆฌ์คํธ๋ก ์
๋ฐ์ดํธ
node.left = nl
# ์ฐ์ธก์์ ๋์จ ๋
ธ๋ ๋ฆฌ์คํธ๋ก ์
๋ฐ์ดํธ
node.right = nr
# ๊ฒฐ๊ณผ ๊ฐ ์ ์ฅ
ans.append(node)
return ans
if __name__ == '__main__':
from common import pp
sol = Solution()
res = sol.allPossibleFBT(5)
for r in res:
print(pp.FullBinaryTreeNodePrettyPrinter.pp(r))
# [[0, 0, 0, None, None, 0, 0, None, None, 0, 0], [0, 0, 0, None, None, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, None, None, None, None, 0, 0],
# [0, 0, 0, 0, 0, None, None, 0, 0]]