
You are given a single integer ‘N’. Your task is to print all possible full binary trees containing ‘N’ nodes. Each node must have 0 as its value.
Note:
A full binary tree is a binary tree where every node has exactly 0 or 2 children.
The first and only line contains a single integer ‘N’, denoting the number of nodes required in each tree.
Output Format:
For each test case, print in a separate line all the nodes of the tree. Trees can be printed in any order but all the nodes of a tree must be printed in level order. If a node does not exist, '-1' should be printed in its place. All the trees must be printed in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 5
1 <= N < 20
Time Limit: 1 sec
1
5
0 0 0 0 0 -1 -1
0 0 0 -1 -1 0 0
For the first test case, the only two possible full binary trees are given below:
We can see that in each tree, the total number of nodes is five and each node either has 0 or 2 children. So both the trees are full binary trees. We can also observe that there is no other full binary tree containing five nodes.
1
3
0 0 0
Think of the number of nodes that the left and right subtrees can have.
Approach:
The approach is to divide the problem into smaller subproblems. We can observe that if there are ‘N’ nodes and the left subtree have ‘X’ nodes then the right subtree will have ‘N-1-X’ nodes. So for all possible values of ‘X’, we can get trees having ‘X’ nodes in the left subtree and ‘N-1-X’ nodes in the right subtree and thus we can combine these and we can get all trees that contain ‘N’ nodes. We can also observe that if ‘N’ is even, we can not have any full binary tree.
Steps:
O(2^N), where 'N' is the number of nodes required in all possible trees.
Every recursive call is making two branches: the first branch calling and returning the list for the left child of all valid full binary trees and the other branch doing the same for the right child. The depth of the recursion tree is the ‘N’, as these recursive calls can go as deep as every number up to ‘N’, in the worst case. So, the time complexity would be O(2 ^ N).
O(2^N), where ‘N’ is the number of nodes required in all possible trees.
Since for ‘2 ^ N’ recursive calls, the recursion stack takes O(2 ^ N) space.