Given an integer n, the task is to find all possible Full Binary Trees with n nodes. The value at the nodes does not contribute to be a criteria for different Full Binary Tree, except for NULL,so take them as 0.
A full binary tree is a binary tree in which every node has exactly 0 or 2 children.
The simplest way to solve the problem is to use recursion using the concept of memoization and check for each subtree if there is a odd number of nodes or not, because a full binary tree has odd nodes.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include<bits/stdc++.h>usingnamespacestd;classNode{public:Node*left;Node*right;intdata;Node(intx){data=x;left=right=nullptr;}};// Function to traverse the tree and add all// the left and right child in the list alvoiddisplay(Node*node,vector<int>&arr){// If node = null then terminate the functionif(node==nullptr){return;}// If there is left child of Node node// then insert it into the list alif(node->left!=nullptr){arr.push_back(node->left->data);}// Otherwise insert null in the listelse{arr.push_back(INT_MIN);}// Similarly, if there is right child// of Node node then insert it into// the list alif(node->right!=nullptr){arr.push_back(node->right->data);}// Otherwise insert nullelse{arr.push_back(INT_MIN);}// Recursively call the function// for left child and right child// of the Node nodedisplay(node->left,arr);display(node->right,arr);}vector<Node*>allPossibleFBT(intn,map<int,vector<Node*>>&mp){// Check whether tree exists for given n// value or not.if(mp.find(n)==mp.end()){// Create a list containing nodesvector<Node*>list;// If N=1, Only one tree can exist// i.e. tree with root.if(n==1){list.push_back(newNode(0));}// Check if N is odd because binary full// tree has N nodeselseif(n%2==1){// Iterate through all the nodes that// can be in the left subtreefor(intx=0;x<n;x++){// Remaining Nodes belongs to the// right subtree of the nodeinty=n-1-x;// Iterate through all left Full Binary Tree// by recursively calling the functionvector<Node*>xallPossibleFBT=allPossibleFBT(x,mp);vector<Node*>yallPossibleFBT=allPossibleFBT(y,mp);for(intLeft=0;Left<xallPossibleFBT.size();Left++){// Iterate through all the right Full// Binary tree by recursively calling// the functionfor(intRight=0;Right<yallPossibleFBT.size();Right++){// Create a new nodeNode*node=newNode(0);// Modify the left nodenode->left=xallPossibleFBT[Left];// Modify the right nodenode->right=yallPossibleFBT[Right];// Add the node in the listlist.push_back(node);}}}}mp.insert({n,list});}returnmp[n];}intmain(){intn=7;map<int,vector<Node*>>mp;vector<Node*>list=allPossibleFBT(n,mp);for(introot=0;root<list.size();root++){vector<int>arr;arr.push_back((list[root])->data);display(list[root],arr);cout<<"[";for(inti=0;i<arr.size();i++){if(i!=arr.size()-1){if(arr[i]==INT_MIN)cout<<"null, ";elsecout<<arr[i]<<", ";}else{if(arr[i]==INT_MIN)cout<<"null]";elsecout<<arr[i]<<"]";}}cout<<endl;}return0;}
Java
// Java program for finding all possible// full binary treesimportjava.util.*;classNode{Nodeleft;Noderight;intdata;Node(intx){data=x;left=right=null;}}classGfG{// Function to traverse the tree and add all// the left and right child in the list alstaticvoiddisplay(Nodenode,List<Integer>al){// If node = null then terminate the functionif(node==null){return;}// If there is left child of Node node// then insert it into the list alif(node.left!=null){al.add(node.left.data);}// Otherwise insert null in the listelse{al.add(Integer.MIN_VALUE);}// Similarly, if there is right child// of Node node then insert it into// the list alif(node.right!=null){al.add(node.right.data);}// Otherwise insert nullelse{al.add(Integer.MIN_VALUE);}// Recursively call the function// for left child and right child// of the Node nodedisplay(node.left,al);display(node.right,al);}staticList<Node>allPossibleFBT(intn,Map<Integer,List<Node>>mp){// Check whether tree exists for given n value or// not.if(!mp.containsKey(n)){List<Node>list=newArrayList<>();// If N=1, Only one tree can exist// i.e. tree with root.if(n==1){list.add(newNode(0));}// Check if N is odd because binary full// tree has N nodeselseif(n%2==1){// Iterate through all the nodes that// can be in the left subtreefor(intx=0;x<n;x++){// Remaining Nodes belongs to the// right subtree of the nodeinty=n-1-x;// Iterate through all left Full Binary// Tree by recursively calling the// functionList<Node>xallPossibleFBT=allPossibleFBT(x,mp);List<Node>yallPossibleFBT=allPossibleFBT(y,mp);for(NodeleftNode:xallPossibleFBT){// Iterate through all the right// Full Binary tree by recursively// calling the functionfor(NoderightNode:yallPossibleFBT){// Create a new nodeNodenode=newNode(0);// Modify the left nodenode.left=leftNode;// Modify the right nodenode.right=rightNode;// Add the node in the listlist.add(node);}}}}mp.put(n,list);}returnmp.get(n);}publicstaticvoidmain(String[]args){intn=7;Map<Integer,List<Node>>mp=newHashMap<>();List<Node>list=allPossibleFBT(n,mp);for(Noderoot:list){List<Integer>al=newArrayList<>();al.add(root.data);display(root,al);System.out.print("[");for(inti=0;i<al.size();i++){if(i!=al.size()-1){System.out.print((al.get(i)==Integer.MIN_VALUE?"null":al.get(i))+", ");}else{System.out.print((al.get(i)==Integer.MIN_VALUE?"null":al.get(i))+"]");}}System.out.println();}}}
Python
# Python program for finding all possible# full binary treesclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=Nonedefdisplay(node,al):# If node = None then terminate# the functionifnodeisNone:return# If there is left child of Node node# then insert it into the list alifnode.leftisnotNone:al.append(node.left.data)else:al.append(None)# Similarly, if there is right child# of Node node then insert it into# the list alifnode.rightisnotNone:al.append(node.right.data)else:al.append(None)# Recursively call the function# for left child and right child# of the Node nodedisplay(node.left,al)display(node.right,al)defallPossibleFBT(n,mp):# Check whether tree exists for # given n value or not.ifnnotinmp:list_=[]# If N=1, Only one tree can exist# i.e. tree with root.ifn==1:list_.append(Node(0))# Check if N is odd because binary full# tree has N nodeselifn%2==1:# Iterate through all the nodes that# can be in the left subtreeforxinrange(n):# Remaining Nodes belongs to the# right subtree of the nodey=n-1-x# Iterate through all left Full Binary Tree# by recursively calling the functionxallPossibleFBT=allPossibleFBT(x,mp)yallPossibleFBT=allPossibleFBT(y,mp)forleftinxallPossibleFBT:# Iterate through all the right Full# Binary tree by recursively calling# the functionforrightinyallPossibleFBT:#Create new nodenode=Node(0)# Modify left subtreenode.left=left# Modify right subtreenode.right=right# Append node to listlist_.append(node)# Memorize the resultmp[n]=list_returnmp[n]if__name__=="__main__":n=7mp={}list_=allPossibleFBT(n,mp)forrootinlist_:al=[root.data]display(root,al)print("[",end="")print(", ".join("null"ifiisNoneelsestr(i)foriinal),end="")print("]")
C#
// C# program for finding all possible // full binary treesusingSystem;usingSystem.Collections.Generic;classNode{publicNodeleft;publicNoderight;publicintdata;publicNode(intx){data=x;left=right=null;}}classGfG{// Function to traverse the tree and add all// the left and right child in the list alstaticvoidDisplay(Nodenode,List<int>arr){// If node is null, terminate the functionif(node==null)return;// If there is a left child of Node// node, insert it into the list alif(node.left!=null){arr.Add(node.left.data);}else{// Otherwise insert int.MinValue// in the list to indicate nullarr.Add(int.MinValue);}// Similarly, if there is a right child of// Node node, insert it into the list alif(node.right!=null){arr.Add(node.right.data);}else{// Otherwise insert int.MinValuearr.Add(int.MinValue);}// Recursively call the function for left and// right children of the Node nodeDisplay(node.left,arr);Display(node.right,arr);}// Function to generate all possible full// binary trees with n nodesstaticList<Node>AllPossibleFBT(intn,Dictionary<int,List<Node>>mp){// Check whether a tree exists for the// given n value in the dictionaryif(!mp.ContainsKey(n)){List<Node>list=newList<Node>();// If N=1, only one tree can exist// with the root node onlyif(n==1){list.Add(newNode(0));}// Check if N is odd, as full binary// trees only have odd numbers of nodeselseif(n%2==1){// Iterate through all nodes that// can be in the left subtreefor(intx=0;x<n;x++){// Remaining nodes belong to the right// subtreeinty=n-1-x;// Recursively generate all// possible left and right subtreesList<Node>xallPossibleFBT=AllPossibleFBT(x,mp);List<Node>yallPossibleFBT=AllPossibleFBT(y,mp);foreach(NodeleftinxallPossibleFBT){// Combine left and right// subtrees with a new root nodeforeach(NoderightinyallPossibleFBT){Nodenode=newNode(0);node.left=left;node.right=right;list.Add(node);}}}}mp[n]=list;}returnmp[n];}staticvoidMain(string[]args){intn=7;Dictionary<int,List<Node>>mp=newDictionary<int,List<Node>>();List<Node>list=AllPossibleFBT(n,mp);foreach(Noderootinlist){List<int>arr=newList<int>{root.data};Display(root,arr);Console.Write("[");for(inti=0;i<arr.Count;i++){Console.Write((arr[i]==int.MinValue?"null":arr[i].ToString())+(i!=arr.Count-1?", ":"]"));}Console.WriteLine();}}}
JavaScript
// JavaScript program for finding all possible full binary// treesclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to traverse the tree and add all the// left and right child in the array alfunctiondisplay(node,al){// If node is null, terminate the functionif(node===null)return;// If there is a left child of Node node,// insert it into the array alif(node.left!==null){al.push(node.left.data);}else{// Otherwise insert null in the array// to represent absence of a left childal.push(null);}// Similarly, if there is a right child of// Node node, insert it into the array alif(node.right!==null){al.push(node.right.data);}else{// Otherwise insert nullal.push(null);}// Recursively call the function for the// left and right children of the Node nodedisplay(node.left,al);display(node.right,al);}// Function to generate all possible full binary trees with// n nodesfunctionallPossibleFBT(n,mp){// Check whether a tree exists for the// given n value in the mapif(!mp.has(n)){letlist=[];// If N=1, only one tree can exist, // with just the root nodeif(n===1){list.push(newNode(0));}// Check if N is odd, as full binary// trees only have odd numbers of nodeselseif(n%2===1){// Iterate through all nodes that// can be in the left subtreefor(letx=0;x<n;x++){// Remaining nodes belong to the right// subtreelety=n-1-x;// Recursively generate all// possible left and right subtreesletxallPossibleFBT=allPossibleFBT(x,mp);letyallPossibleFBT=allPossibleFBT(y,mp);for(letleftofxallPossibleFBT){// Combine left and right// subtrees with a new root nodefor(letrightofyallPossibleFBT){letnode=newNode(0);node.left=left;node.right=right;list.push(node);}}}}mp.set(n,list);}returnmp.get(n);}letn=7;letmp=newMap();letlist=allPossibleFBT(n,mp);for(letrootoflist){letal=[root.data];display(root,al);console.log("["+al.map(val=>val===null?"null":val).join(", ")+"]");}