Skip to content

Commit 9b6cd2c

Browse files
authored
Create all-possible-full-binary-trees.py
1 parent f6adbbb commit 9b6cd2c

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Time: O(n * 4^n / n^(3/2)) ~= Catalan numbers
2+
# Space: O(n * 4^n / n^(3/2)) ~= Catalan numbers
3+
4+
# A full binary tree is a binary tree where each node has exactly 0 or 2 children.
5+
#
6+
# Return a list of all possible full binary trees with N nodes.
7+
# Each element of the answer is the root node of one possible tree.
8+
#
9+
# Each node of each tree in the answer must have node.val = 0.
10+
#
11+
# You may return the final list of trees in any order.
12+
#
13+
# Example 1:
14+
#
15+
# Input: 7
16+
# Output: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],
17+
# [0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]
18+
# Explanation:
19+
#
20+
# Note:
21+
# - 1 <= N <= 20
22+
23+
# Definition for a binary tree node.
24+
class TreeNode(object):
25+
def __init__(self, x):
26+
self.val = x
27+
self.left = None
28+
self.right = None
29+
30+
31+
class Solution(object):
32+
def __init__(self):
33+
self.__memo = {1: [TreeNode(0)]}
34+
35+
def allPossibleFBT(self, N):
36+
"""
37+
:type N: int
38+
:rtype: List[TreeNode]
39+
"""
40+
if N % 2 == 0:
41+
return []
42+
43+
if N not in self.__memo:
44+
result = []
45+
for i in xrange(N):
46+
for left in self.allPossibleFBT(i):
47+
for right in self.allPossibleFBT(N-1-i):
48+
node = TreeNode(0)
49+
node.left = left
50+
node.right = right
51+
result.append(node)
52+
self.__memo[N] = result
53+
54+
return self.__memo[N]
55+

0 commit comments

Comments
 (0)