LeetCode 0894. All Possible Full Binary Trees Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0894. All Possible Full Binary Trees

Description

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

Solutions

Solution 1: Memoization Search

If n=1, return a list with a single node directly.

If n > 1, we can enumerate the number of nodes i in the left subtree, then the number of nodes in the right subtree is n-1-i. For each case, we recursively construct all possible genuine binary trees for the left and right subtrees. Then we combine the left and right subtrees in pairs to get all possible genuine binary trees.

This process can be optimized with memoization search to avoid repeated calculations.

The time complexity is O(2n√n), and the space complexity is O(2n√n). Where n is the number of nodes.

PythonJavaC++GoTypeScriptRustC#
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]: @cache def dfs(n: int) -> List[Optional[TreeNode]]: if n == 1: return [TreeNode()] ans = [] for i in range(n - 1): j = n - 1 - i for left in dfs(i): for right in dfs(j): ans.append(TreeNode(0, left, right)) return ans return dfs(n)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !