Given an integer n
, return a list of all possible full binary trees with n
nodes. Each node of each tree in the answer must have Node.val == 0
.
Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order.
A full binary tree is a binary tree where each node has exactly 0
or 2
children.
Example 1:

Input: n = 7 Output: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[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]]
Example 2:
Input: n = 3 Output: [[0,0,0]]
Constraints:
1 <= n <= 20
Solution :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution(object): | |
dp = {0:[],1:[TreeNode(0)]} | |
def allPossibleFBT(self, n): | |
if n in Solution.dp: | |
return Solution.dp[n] | |
ans = [] | |
for i in range(n): | |
j = n-1-i | |
for l in self.allPossibleFBT(i): | |
for r in self.allPossibleFBT(j): | |
bns = TreeNode(0) | |
bns.left = l | |
bns.right = r | |
ans.append(bns) | |
Solution.dp[n]=ans | |
return ans | |
No comments:
Post a Comment