Create Binary Tree from given Array of relation between nodes
Last Updated : 29 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report
Given a 2D integer array where each row represents the relation between the nodes (relation[i] = [parenti, childi, isLefti]). The task is to construct the binary tree described by the 2D matrix and print the LevelOrder Traversal of the formed Binary Tree.
Examples:
Input: Relation[] = [[20, 15, 1], [20, 17, 0], [50, 20, 1], [50, 80, 0], [80, 19, 1]] Output: [50, 20, 80, 15, 17, 19] Explanation: The root node is the node with the value 50 since it has no parent.
Example1
Input: Relation[] = [[1, 2, 1], [2, 3, 0], [3, 4, 1]] Output: [1, 2, 3, 4] Explanation: The root node is the node with the value 1 since it has no parent.
Example 2
Approach: To solve the problem follow the below idea:
Iterate over the given 2D matrix(Relation Array) and see if the parent Node is present in the map or not.
Follow the Below steps to solve the above approach:
Create a map data Structure that will store the address of each of the nodes formed with their values.
Iterate over the given 2D matrix(Relation Array) and see if the parentNode is present in the map or not.
If the parentNode is present in the map then there is no need of making a new node, Just store the address of the parentNode in a variable.
If the parentNode is not present in the map then form a parentNode of the given value and store its address in the map. (Because this parentNode can be the childNode of some other Node).
Similarly, Repeat Step 2 for child Node also i.e.,
If the childNode is present in the map then there is no need of making a new node, Just store the address of the childNode in a variable.
If the childNode is not present in the map then form a childNode of the given value and store its address in the map(Because this childNode can be the parentNode of some other Node).
Form the relation between the parentNode and the childNode for each iteration depending on the value of the third value of the array of each iteration. i.e.,
If the third value of the array in the given iteration is 1 then it means that the childNode is the left child of the parentNode formed for the given iteration.
If the third value of the array in the given iteration is 0 then it means that the childNode is the left child of the parentNode formed for the given iteration.
If carefully observed we know that the root node is the only node that has no Parent.
Store all the values of the childNode that is present in the given 2D matrix (Relation Array) in a data structure (let's assume a map data structure).
Again iterate the 2D matrix (RelationArray) to check which parentNode value is not present in the map data structure formed in step 5).
Print the level Order Traversal of the thus-formed tree.
Below is the implementation of the above approach.
C++
// C++ code for the above approach:#include<bits/stdc++.h>usingnamespacestd;// Binary Tree NodestructNode{intdata;Node*left,*right;};// Returns new Node with data as input// to below function.Node*newNode(intd){Node*temp=newNode;temp->data=d;temp->left=nullptr;temp->right=nullptr;returntemp;}// Function to create tree from// given descriptionNode*createBinaryTree(vector<vector<int>>&descriptions){unordered_map<int,Node*>mp;for(autoit:descriptions){Node*parentNode,*childNode;// Check if the parent Node is// already formed or notif(mp.find(it[0])!=mp.end()){parentNode=mp[it[0]];}else{parentNode=newNode(it[0]);mp[it[0]]=parentNode;}// Check if the child Node is// already formed or notif(mp.find(it[1])!=mp.end()){childNode=mp[it[1]];}else{childNode=newNode(it[1]);mp[it[1]]=childNode;}// Making the Edge Between parent// and child Nodeif(it[2]==1){parentNode->left=childNode;}else{parentNode->right=childNode;}}// Store the childNodeunordered_map<int,int>storeChild;for(autoit:descriptions){storeChild[it[1]]=1;}// Find the root of the TreeNode*root;for(autoit:descriptions){if(storeChild.find(it[0])==storeChild.end()){root=mp[it[0]];}}returnroot;}// Level order TraversalvoidprintLevelOrder(Node*root){// Base Caseif(root==nullptr){return;}// Create an empty queue for// level order traversalqueue<Node*>q;// Enqueue Root and initialize heightq.push(root);while(q.empty()==false){// Print front of queue and// remove it from queueNode*node=q.front();cout<<node->data<<" ";q.pop();// Enqueue left childif(node->left!=nullptr){q.push(node->left);}// Enqueue right childif(node->right!=nullptr){q.push(node->right);}}}// Driver Codeintmain(){vector<vector<int>>RelationArray={{20,15,1},{20,17,0},{50,20,1},{50,80,0},{80,19,1}};Node*root=createBinaryTree(RelationArray);printLevelOrder(root);cout<<endl;vector<vector<int>>RelationArray2={{1,2,1},{2,3,0},{3,4,1}};Node*root2=createBinaryTree(RelationArray2);printLevelOrder(root2);return0;}
Java
// Java code for the above approach:importjava.io.*;importjava.util.*;// Binary Tree NodeclassNode{intdata;Nodeleft,right;Node(intd){data=d;left=right=null;}}classGFG{// Returns new Node with data as input// to below function.staticNodenewNode(intd){Nodetemp=newNode(d);temp.left=null;temp.right=null;returntemp;}// Function to create tree from// given descriptionstaticNodecreateBinaryTree(List<List<Integer>>descriptions){Map<Integer,Node>mp=newHashMap<>();for(List<Integer>it:descriptions){NodeparentNode,childNode;// Check if the parent Node is// already formed or notif(mp.containsKey(it.get(0))){parentNode=mp.get(it.get(0));}else{parentNode=newNode(it.get(0));mp.put(it.get(0),parentNode);}// Check if the child Node is// already formed or notif(mp.containsKey(it.get(1))){childNode=mp.get(it.get(1));}else{childNode=newNode(it.get(1));mp.put(it.get(1),childNode);}// Making the Edge Between parent// and child Nodeif(it.get(2)==1){parentNode.left=childNode;}else{parentNode.right=childNode;}}// Store the childNodeMap<Integer,Integer>storeChild=newHashMap<>();for(List<Integer>it:descriptions){storeChild.put(it.get(1),1);}// Find the root of the TreeNoderoot=null;for(List<Integer>it:descriptions){if(!storeChild.containsKey(it.get(0))){root=mp.get(it.get(0));}}returnroot;}// Level order TraversalstaticvoidprintLevelOrder(Noderoot){// Base Caseif(root==null){return;}// Create an empty queue for// level order traversalQueue<Node>q=newLinkedList<>();// Enqueue Root and initialize heightq.add(root);while(!q.isEmpty()){// Print front of queue and// remove it from queueNodenode=q.peek();System.out.print(node.data+" ");q.poll();// Enqueue left childif(node.left!=null){q.add(node.left);}// Enqueue right childif(node.right!=null){q.add(node.right);}}}publicstaticvoidmain(String[]args){List<List<Integer>>RelationArray=Arrays.asList(Arrays.asList(20,15,1),Arrays.asList(20,17,0),Arrays.asList(50,20,1),Arrays.asList(50,80,0),Arrays.asList(80,19,1));Noderoot=createBinaryTree(RelationArray);printLevelOrder(root);System.out.println();List<List<Integer>>RelationArray2=Arrays.asList(Arrays.asList(1,2,1),Arrays.asList(2,3,0),Arrays.asList(3,4,1));Noderoot2=createBinaryTree(RelationArray2);printLevelOrder(root2);}}// This code is contributed by lokeshmvs21.
Python3
# Python code for the above approachfromtypingimportList# Binary Tree NodeclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Returns new Node with data as input# to below function.defnewNode(d):temp=Node(d)returntemp# Function to create tree from# given descriptiondefcreateBinaryTree(descriptions:List[List[int]])->Node:mp={}foritindescriptions:parentNode,childNode=None,None# Check if the parent Node is# already formed or notifit[0]inmp:parentNode=mp[it[0]]else:parentNode=newNode(it[0])mp[it[0]]=parentNode# Check if the child Node is# already formed or notifit[1]inmp:childNode=mp[it[1]]else:childNode=newNode(it[1])mp[it[1]]=childNode# Making the Edge Between parent# and child Nodeifit[2]==1:parentNode.left=childNodeelse:parentNode.right=childNode# Store the childNodestoreChild={}foritindescriptions:storeChild[it[1]]=1# Find the root of the Treeroot=Noneforitindescriptions:ifit[0]notinstoreChild:root=mp[it[0]]returnroot# Level order TraversaldefprintLevelOrder(root:Node):# Base CaseifrootisNone:return# Create an empty queue for# level order traversalq=[]# Enqueue Root and initialize heightq.append(root)whilelen(q)>0:# Print front of queue and# remove it from queuenode=q.pop(0)print(node.data,end=' ')# Enqueue left childifnode.leftisnotNone:q.append(node.left)# Enqueue right childifnode.rightisnotNone:q.append(node.right)# Driver Codeif__name__=="__main__":relationArray=[[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]root=createBinaryTree(relationArray)printLevelOrder(root)print()relationArray2=[[1,2,1],[2,3,0],[3,4,1]]root2=createBinaryTree(relationArray2)printLevelOrder(root2)# This code is contributed by Potta Lokesh
C#
// C# code for the above approach:usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;// Binary Tree NodeclassNode{publicintdata;publicNodeleft,right;publicNode(intdata){this.data=data;this.left=null;this.right=null;}}publicclassGFG{// Returns new Node with data as input// to below function.staticNodeNewNode(intdata){Nodetemp=newNode(data);temp.left=null;temp.right=null;returntemp;}// Function to create tree from// given descriptionstaticNodeCreateBinaryTree(List<List<int>>descriptions){Dictionary<int,Node>mp=newDictionary<int,Node>();foreach(List<int>itindescriptions){NodeparentNode,childNode;// Check if the parent Node is// already formed or notif(mp.ContainsKey(it[0])){parentNode=mp[it[0]];}else{parentNode=NewNode(it[0]);mp[it[0]]=parentNode;}// Check if the child Node is// already formed or notif(mp.ContainsKey(it[1])){childNode=mp[it[1]];}else{childNode=NewNode(it[1]);mp[it[1]]=childNode;}// Making the Edge Between parent// and child Nodeif(it[2]==1){parentNode.left=childNode;}else{parentNode.right=childNode;}}// Store the childNodeDictionary<int,int>storeChild=newDictionary<int,int>();foreach(List<int>itindescriptions){storeChild[it[1]]=1;}// Find the root of the TreeNoderoot=null;foreach(List<int>itindescriptions){if(!storeChild.ContainsKey(it[0])){root=mp[it[0]];}}returnroot;}// Level order TraversalstaticvoidPrintLevelOrder(Noderoot){// Base Caseif(root==null){return;}// Create an empty queue for// level order traversalQueue<Node>q=newQueue<Node>();// Enqueue Root and initialize heightq.Enqueue(root);while(q.Count>0){// Print front of queue and// remove it from queueNodenode=q.Peek();Console.Write(node.data+" ");q.Dequeue();// Enqueue left childif(node.left!=null){q.Enqueue(node.left);}// Enqueue right childif(node.right!=null){q.Enqueue(node.right);}}}staticpublicvoidMain(){List<List<int>>RelationArray=newList<List<int>>{newList<int>{20,15,1},newList<int>{20,17,0},newList<int>{50,20,1},newList<int>{50,80,0},newList<int>{80,19,1}};Noderoot=CreateBinaryTree(RelationArray);PrintLevelOrder(root);Console.WriteLine();List<List<int>>RelationArray2=newList<List<int>>{newList<int>{1,2,1},newList<int>{2,3,0},newList<int>{3,4,1}};Noderoot2=CreateBinaryTree(RelationArray2);PrintLevelOrder(root2);}}// This code is contributed by lokesh.
JavaScript
// JavaScript Code for the above approach// Node ClassclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Function to create tree from given descriptionfunctioncreateBinaryTree(descriptions){letmp=newMap();for(letitofdescriptions){letparentNode,childNode;// Check if the parent Node is// already formed or notif(mp.has(it[0])){parentNode=mp.get(it[0]);}else{parentNode=newNode(it[0]);mp.set(it[0],parentNode);}// Check if the child Node is// already formed or notif(mp.has(it[1])){childNode=mp.get(it[1]);}else{childNode=newNode(it[1]);mp.set(it[1],childNode);}// Making the Edge Between parent// and child Nodeif(it[2]==1){parentNode.left=childNode;}else{parentNode.right=childNode;}}// Store the childNodeletstoreChild=newMap();for(letitofdescriptions){storeChild.set(it[1],1);}// Find the root of the Treeletroot;for(letitofdescriptions){if(!storeChild.has(it[0])){root=mp.get(it[0]);}}returnroot;}// Level order TraversalfunctionprintLevelOrder(root){// Base Caseif(root==null){return;}// Create an empty queue for// level order traversalletq=[];// Enqueue Root and initialize heightq.push(root);while(q.length>0){// Print front of queue and// remove it from queueletnode=q.shift();console.log(node.data+" ");// Enqueue left childif(node.left!=null){q.push(node.left);}// Enqueue right childif(node.right!=null){q.push(node.right);}}}// Driver CodeletRelationArray=[[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1],];letroot=createBinaryTree(RelationArray);printLevelOrder(root);letRelationArray2=[[1,2,1],[2,3,0],[3,4,1],];letroot2=createBinaryTree(RelationArray2);printLevelOrder(root2);// This code is contributed by adityamaharshi21
Output
50 20 80 15 17 19 1 2 3 4
Time Complexity: O(N) where N is the number of rows present in the 2D matrix + O(M) where M is the number of nodes present in the Tree (for Level Order Traversal) Auxiliary Space: O(M) where M is the number of nodes present in the Tree (We are storing the values of the nodes along with their address in the map).
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.