Construct a tree from Inorder and Level order traversals | Set 2
Given inorder and level-order traversals of a Binary Tree, construct the Binary Tree. Following is an example to illustrate the problem.
Examples:
Input: Two arrays that represent Inorder and level order traversals of a Binary Tree in[] = {4, 8, 10, 12, 14, 20, 22}; level[] = {20, 8, 22, 4, 12, 10, 14}; Output: Construct the tree represented by the two arrays. For the above two arrays, the constructed tree is shown.
We have discussed a solution in below post that works in O(N^3)
Construct a tree from Inorder and Level order traversals | Set 1
Approach: Following algorithm uses O(N^2) time complexity to solve the above problem using the unordered_set data structure in c++ (basically making a hash-table) to put the values of left subtree of the current root and later and we will check in O(1) complexity to find if the current levelOrder node is part of left subtree or not.
If it is the part of left subtree then add in one lLevel array for left otherwise add it to rLevel array for right subtree.
Below is the implementation with the above idea :
C++
/* program to construct tree using inorder and levelorder traversals */ #include <bits/stdc++.h> using namespace std; /* A binary tree node */ struct Node { int key; struct Node* left, *right; }; Node* makeNode( int data){ Node* newNode = new Node(); newNode->key = data; newNode->right = newNode->right = NULL; return newNode; } // Function to build tree from given // levelorder and inorder Node* buildTree( int inorder[], int levelOrder[], int iStart, int iEnd, int n) { if (n <= 0) return NULL; // First node of level order is root Node* root = makeNode(levelOrder[0]); // Search root in inorder int index = -1; for ( int i=iStart; i<=iEnd; i++){ if (levelOrder[0] == inorder[i]){ index = i; break ; } } // Insert all left nodes in hash table unordered_set< int > s; for ( int i=iStart;i<index;i++) s.insert(inorder[i]); // Separate level order traversals // of left and right subtrees. int lLevel[s.size()]; // Left int rLevel[iEnd-iStart-s.size()]; // Right int li = 0, ri = 0; for ( int i=1;i<n;i++) { if (s.find(levelOrder[i]) != s.end()) lLevel[li++] = levelOrder[i]; else rLevel[ri++] = levelOrder[i]; } // Recursively build left and right // subtrees and return root. root->left = buildTree(inorder, lLevel, iStart, index-1, index-iStart); root->right = buildTree(inorder, rLevel, index+1, iEnd, iEnd-index); return root; } /* Utility function to print inorder traversal of binary tree */ void printInorder(Node* node) { if (node == NULL) return ; printInorder(node->left); cout << node->key << " " ; printInorder(node->right); } // Driver Code int main() { int in[] = {4, 8, 10, 12, 14, 20, 22}; int level[] = {20, 8, 22, 4, 12, 10, 14}; int n = sizeof (in)/ sizeof (in[0]); Node *root = buildTree(in, level, 0, n - 1, n); /* Let us test the built tree by printing Inorder traversal */ cout << "Inorder traversal of the " "constructed tree is \n" ; printInorder(root); return 0; } |
Java
/* * program to construct tree using inorder * and levelorder traversals */ import java.util.HashSet; class GFG { /* A binary tree node */ static class Node { int key; Node left, right; }; static Node makeNode( int data) { Node newNode = new Node(); newNode.key = data; newNode.right = newNode.right = null ; return newNode; } // Function to build tree from given // levelorder and inorder static Node buildTree( int inorder[], int levelOrder[], int iStart, int iEnd, int n) { if (n <= 0 ) return null ; // First node of level order is root Node root = makeNode(levelOrder[ 0 ]); // Search root in inorder int index = - 1 ; for ( int i = iStart; i <= iEnd; i++) { if (levelOrder[ 0 ] == inorder[i]) { index = i; break ; } } // Insert all left nodes in hash table HashSet<Integer> s = new HashSet<>(); for ( int i = iStart; i < index; i++) s.add(inorder[i]); // Separate level order traversals // of left and right subtrees. int [] lLevel = new int [s.size()]; // Left int [] rLevel = new int [iEnd - iStart - s.size()]; // Right int li = 0 , ri = 0 ; for ( int i = 1 ; i < n; i++) { if (s.contains(levelOrder[i])) lLevel[li++] = levelOrder[i]; else rLevel[ri++] = levelOrder[i]; } // Recursively build left and right // subtrees and return root. root.left = buildTree(inorder, lLevel, iStart, index - 1 , index - iStart); root.right = buildTree(inorder, rLevel, index + 1 , iEnd, iEnd - index); return root; } /* * Utility function to print inorder * traversal of binary tree */ static void printInorder(Node node) { if (node == null ) return ; printInorder(node.left); System.out.print(node.key + " " ); printInorder(node.right); } // Driver Code public static void main(String[] args) { int in[] = { 4 , 8 , 10 , 12 , 14 , 20 , 22 }; int level[] = { 20 , 8 , 22 , 4 , 12 , 10 , 14 }; int n = in.length; Node root = buildTree(in, level, 0 , n - 1 , n); /* * Let us test the built tree by * printing Inorder traversal */ System.out.println( "Inorder traversal of the constructed tree is " ); printInorder(root); } } // This code is contributed by sanjeev2552 |
Python3
# program to construct tree using inorder and levelorder traversals import collections class Node: # A binary tree node def __init__( self , key): self .key = key self .left = None self .right = None def makeNode(data): newNode = Node(data) return newNode # Function to build tree from given levelorder and inorder def buildTree(inorder, levelOrder, iStart, iEnd): n = len (levelOrder) if n < = 0 : return None # First node of level order is root root = makeNode(levelOrder[ 0 ]) # Search root in inorder index = - 1 for i in range (iStart, iEnd + 1 ): if levelOrder[ 0 ] = = inorder[i]: index = i break # Insert all left nodes in hash table s = set () for i in range (iStart, index): s.add(inorder[i]) # Separate level order traversals of left and right subtrees. lLevel = [] rLevel = [] li = 0 ri = 0 for i in range ( 1 , n): if levelOrder[i] in s: lLevel.append(levelOrder[i]) li + = 1 else : rLevel.append(levelOrder[i]) ri + = 1 # Recursively build left and right subtrees and return root root.left = buildTree(inorder, lLevel, iStart, index - 1 ) root.right = buildTree(inorder, rLevel, index + 1 , iEnd) return root # Utility function to print inorder traversal of binary tree def printInorder(node): if node is None : return printInorder(node.left) print (node.key, end = ' ' ) printInorder(node.right) # Driver Code if __name__ = = '__main__' : inOrder = [ 4 , 8 , 10 , 12 , 14 , 20 , 22 ] levelOrder = [ 20 , 8 , 22 , 4 , 12 , 10 , 14 ] n = len (inOrder) root = buildTree(inOrder, levelOrder, 0 , n - 1 ) # Let us test the built tree by printing Inorder traversal print ( "Inorder traversal of the constructed tree is " ) printInorder(root) |
C#
/* * program to construct tree using inorder * and levelorder traversals */ using System; using System.Collections; using System.Collections.Generic; class GFG { /* A binary tree node */ public class Node { public int key; public Node left, right; }; static Node makeNode( int data) { Node newNode = new Node(); newNode.key = data; newNode.right = newNode.right = null ; return newNode; } // Function to build tree from given // levelorder and inorder static Node buildTree( int [] inorder, int [] levelOrder, int iStart, int iEnd, int n) { if (n <= 0) return null ; // First node of level order is root Node root = makeNode(levelOrder[0]); // Search root in inorder int index = -1; for ( int i = iStart; i <= iEnd; i++) { if (levelOrder[0] == inorder[i]) { index = i; break ; } } // Insert all left nodes in hash table HashSet< int > s = new HashSet< int >(); for ( int i = iStart; i < index; i++) s.Add(inorder[i]); // Separate level order traversals // of left and right subtrees. int [] lLevel = new int [s.Count]; // Left int [] rLevel = new int [iEnd - iStart - s.Count]; // Right int li = 0, ri = 0; for ( int i = 1; i < n; i++) { if (s.Contains(levelOrder[i])) lLevel[li++] = levelOrder[i]; else rLevel[ri++] = levelOrder[i]; } // Recursively build left and right // subtrees and return root. root.left = buildTree(inorder, lLevel, iStart, index - 1, index - iStart); root.right = buildTree(inorder, rLevel, index + 1, iEnd, iEnd - index); return root; } /* * Utility function to print inorder * traversal of binary tree */ static void printInorder(Node node) { if (node == null ) return ; printInorder(node.left); Console.Write(node.key + " " ); printInorder(node.right); } // Driver Code public static void Main( string [] args) { int [] inorder = new int [] { 4, 8, 10, 12, 14, 20, 22 }; int [] level = new int [] { 20, 8, 22, 4, 12, 10, 14 }; int n = inorder.Length; Node root = buildTree(inorder, level, 0, n - 1, n); /* * Let us test the built tree by * printing Inorder traversal */ Console.WriteLine( "Inorder traversal of the constructed tree is " ); printInorder(root); } } // This code is contributed by Karandeep1234 |
Javascript
<script> /* program to construct tree using inorder and levelorder traversals */ /* A binary tree node */ class Node { constructor(data) { this .left = null ; this .right = null ; this .key = data; } } function makeNode(data) { let newNode = new Node(data); return newNode; } // Function to build tree from given // levelorder and inorder function buildTree(inorder, levelOrder, iStart, iEnd, n) { if (n <= 0) return null ; // First node of level order is root let root = makeNode(levelOrder[0]); // Search root in inorder let index = -1; for (let i = iStart; i <= iEnd; i++) { if (levelOrder[0] == inorder[i]) { index = i; break ; } } // Insert all left nodes in hash table let s = new Set(); for (let i = iStart; i < index; i++) s.add(inorder[i]); // Separate level order traversals // of left and right subtrees. let lLevel = new Array(s.size); // Left let rLevel = new Array(iEnd - iStart - s.size); // Right let li = 0, ri = 0; for (let i = 1; i < n; i++) { if (s.has(levelOrder[i])) lLevel[li++] = levelOrder[i]; else rLevel[ri++] = levelOrder[i]; } // Recursively build left and right // subtrees and return root. root.left = buildTree(inorder, lLevel, iStart, index - 1, index - iStart); root.right = buildTree(inorder, rLevel, index + 1, iEnd, iEnd - index); return root; } /* * Utility function to print inorder * traversal of binary tree */ function printInorder(node) { if (node == null ) return ; printInorder(node.left); document.write(node.key + " " ); printInorder(node.right); } let In = [ 4, 8, 10, 12, 14, 20, 22 ]; let level = [ 20, 8, 22, 4, 12, 10, 14 ]; let n = In.length; let root = buildTree(In, level, 0, n - 1, n); /* * Let us test the built tree by * printing Inorder traversal */ document.write( "Inorder traversal of the constructed tree is " + "</br>" ); printInorder(root); </script> |
Inorder traversal of the constructed tree is 4 8 10 12 14 20 22
Time Complexity: O(N^2)
Optimization: Without separate level order traversal arrays of left and right subtrees.
Approach: Using Hashing.
Use a HashMap to store the indices of level order traversal. In the range of start & end from inorder, search the element with the least index from the level order map. Create left and right subtrees recursively.
index -> the least index for left subtree: start to index-1 for right subtree: index+1 to end
Implementation:
C++
// C++ Program to implement above approach #include <bits/stdc++.h> using namespace std; // Node Structure struct Node { int data; Node* left; Node* right; Node( int data) { this ->data = data; this ->left = NULL; this ->right = NULL; } }; map< int , int > mp; // function to construct hashmap void constructMap( int level[], int n) { for ( int i = 0; i < n; i++) { mp[level[i]] = i; } } // function to construct binary tree from inorder and // levelorder traversal Node* construct( int in[], int start, int end) { // if start is greater than end return null if (start > end) return NULL; int min_index = start; // In the range of start & end from inorder, search the // element with least index from level order map for ( int i = start + 1; i <= end; i++) { int temp = in[i]; // if current element from inorder have least index // in levelorder map, update min_index if (mp[in[min_index]] > mp[temp]) min_index = i; } // create a node with current element Node* root = new Node(in[min_index]); // if start is equal to end, then return root if (start == end) return root; // construct left and right subtrees root->left = construct(in, start, min_index - 1); root->right = construct(in, min_index + 1, end); return root; } // Function to print inorder traversal void printInorder(Node* node) { if (node == NULL) return ; printInorder(node->left); cout << node->data << " " ; printInorder(node->right); } // Driver Function int main() { int in[] = { 4, 8, 10, 12, 14, 20, 22 }; int level[] = { 20, 8, 22, 4, 12, 10, 14 }; int size = sizeof (level) / sizeof (level[0]); // function calls constructMap(level, size); int n = mp.size(); Node* root = construct(in, 0, n - 1); printInorder(root); return 0; } // This code is contributed by Yash // Agarwal(yashagarwal2852002) |
Java
import java.util.HashMap; //class Node class Node{ int data; Node left,right; Node( int data){ this .data = data; left = right = null ; } } public class ConstructTree { //hashmap to store the indices of levelorder array HashMap<Integer,Integer> map = new HashMap<>(); //function to construct hashmap void constructMap( int level[]) { for ( int i= 0 ;i<level.length;i++) map.put(level[i], i); } //function to construct binary tree from inorder and levelorder Node construct( int in[], int start, int end) { //if start is greater than end return null if (start > end) return null ; int min_index = start; //In the range of start & end from inorder, search the element //with least index from level order map for ( int i=start+ 1 ;i<=end;i++) { int temp = in[i]; //if current element from inorder have least index in //levelorder map, update min_index if (map.get(in[min_index]) > map.get(temp)) min_index = i; } //create a node with current element Node root = new Node(in[min_index]); //if start is equal to end, then return root if (start == end) return root; //construct left and right subtrees root.left = construct(in,start,min_index- 1 ); root.right = construct(in,min_index+ 1 ,end); return root; } //function to print inorder void printInorder(Node node) { if (node == null ) return ; printInorder(node.left); System.out.print(node.data + " " ); printInorder(node.right); } //Driver function public static void main(String[] args) { ConstructTree tree = new ConstructTree(); int in[] = { 4 , 8 , 10 , 12 , 14 , 20 , 22 }; int level[] = { 20 , 8 , 22 , 4 , 12 , 10 , 14 }; //function calls tree.constructMap(level); int n = level.length; Node root = tree.construct(in, 0 , n- 1 ); tree.printInorder(root); } } //This method is contributed by Likhita AVL |
Python3
from typing import List from collections import deque # class Node class Node: def __init__( self , data): self .data = data self .left = None self .right = None class ConstructTree: def __init__( self ): # dictionary to store the indices of levelorder array self . map = {} # function to construct hashmap def constructMap( self , level: List [ int ]) - > None : for i in range ( len (level)): self . map [level[i]] = i # function to construct binary tree from inorder and levelorder def construct( self , in_: List [ int ], start: int , end: int ) - > Node: # if start is greater than end return None if start > end: return None min_index = start # In the range of start & end from inorder, search the element # with least index from level order map for i in range (start + 1 , end + 1 ): temp = in_[i] # if current element from inorder have least index in # levelorder map, update min_index if self . map [in_[min_index]] > self . map [temp]: min_index = i # create a node with current element root = Node(in_[min_index]) # if start is equal to end, then return root if start = = end: return root # construct left and right subtrees root.left = self .construct(in_, start, min_index - 1 ) root.right = self .construct(in_, min_index + 1 , end) return root # function to print inorder def printInorder( self , node: Node) - > None : if node is None : return self .printInorder(node.left) print (node.data, end = " " ) self .printInorder(node.right) # Driver function def main( self ) - > None : tree = ConstructTree() in_ = [ 4 , 8 , 10 , 12 , 14 , 20 , 22 ] level = [ 20 , 8 , 22 , 4 , 12 , 10 , 14 ] # function calls tree.constructMap(level) n = len (level) root = tree.construct(in_, 0 , n - 1 ) tree.printInorder(root) if __name__ = = "__main__" : t = ConstructTree() t.main() |
C#
using System; using System.Collections.Generic; public class Node { public int data; public Node left, right; public Node( int data) { this .data = data; left = right = null ; } } public class BinaryTree { public static Dictionary< int , int > mp = new Dictionary< int , int >(); // function to construct hashmap public static void constructMap( int [] level, int n) { for ( int i = 0; i < n; i++) { mp[level[i]] = i; } } // function to construct binary tree from inorder and // levelorder traversal public static Node construct( int [] inOrder, int start, int end) { // if start is greater than end return null if (start > end) return null ; int min_index = start; // In the range of start & end from inorder, search the // element with least index from level order map for ( int i = start + 1; i <= end; i++) { int temp = inOrder[i]; // if current element from inorder have least index // in levelorder map, update min_index if (mp[inOrder[min_index]] > mp[temp]) min_index = i; } // create a node with current element Node root = new Node(inOrder[min_index]); // if start is equal to end, then return root if (start == end) return root; // construct left and right subtrees root.left = construct(inOrder, start, min_index - 1); root.right = construct(inOrder, min_index + 1, end); return root; } // Function to print inorder traversal public static void printInorder(Node node) { if (node == null ) return ; printInorder(node.left); Console.Write(node.data + " " ); printInorder(node.right); } // Driver Function public static void Main() { int [] inOrder = { 4, 8, 10, 12, 14, 20, 22 }; int [] levelOrder = { 20, 8, 22, 4, 12, 10, 14 }; int n = levelOrder.Length; // function calls constructMap(levelOrder, n); Node root = construct(inOrder, 0, n - 1); printInorder(root); } } |
Javascript
// JavaScript program to implement above approach // Node structure class Node{ constructor(data){ this .data = data; this .left = null ; this .right = null ; } } let mp = new Map(); // function to construct hashmap function constructMap(level, n){ for (let i = 0; i<n; i++){ mp.set(level[i], i); } } // function to construct binary tree from inorder and // levelorder traversal function construct(IN, start, end){ // if start is greater then end return null if (start > end) return null ; let min_index = start; // In the range of start and end from inorder, search the // element with least index from level order map for (let i = start+1; i<=end; i++){ let temp = IN[i]; // if current element from inorder have least index // in levelroder map, update min_index if (mp.get(IN[min_index]) > mp.get(temp)){ min_index = i; } } // create a node with current element let root = new Node(IN[min_index]); // if start is equal to end, then return root if (start == end) return root; // construct left and right subtrees root.left = construct(IN, start, min_index-1); root.right = construct(IN, min_index+1, end); return root; } // function to print inorder traversal function printInorder(node){ if (node == null ) return ; printInorder(node.left); console.log(node.data + " " ); printInorder(node.right); } // driver function let IN = [4, 8, 10, 12, 14, 20, 22]; let level = [20, 8, 22, 4, 12, 10, 14]; let size = level.length; // function calls constructMap(level, size); let n = mp.size; let root = construct(IN, 0, n-1); printInorder(root); // this code is contributed by Kirit Agarwal(kirtiagarwal23121999) |
4 8 10 12 14 20 22
Time Complexity: O(n^2).
Another approach using queue.
C++
//{ Driver Code Starts #include <bits/stdc++.h> using namespace std; struct Node { int key; struct Node* left; struct Node* right; Node( int x) { key = x; left = NULL; right = NULL; } }; Node* buildTree( int inorder[], int levelOrder[], int iStart, int iEnd, int n); void printInorder(Node* node) { if (node == NULL) return ; printInorder(node->left); cout << node->key << " " ; printInorder(node->right); } int main() { int n = 7; int in[] = { 4, 8, 10, 12, 14, 20, 22 }; int level[] = { 20, 8, 22, 4, 12, 10, 14 }; Node* root = NULL; root = buildTree(in, level, 0, n - 1, n); printInorder(root); cout << endl; return 0; } // } Driver Code Ends /*Complete the function below Node is as follows: struct Node { int key; struct Node* left, *right; }; */ Node* buildTree( int inorder[], int levelOrder[], int iStart, int iEnd, int n) { queue<pair<Node*, pair< int , int > > > q; unordered_map< int , int > mp; for ( int i = 0; i < n; i++) mp[inorder[i]] = i; int idx = 0; Node* root = new Node(levelOrder[idx++]); q.push({ root, { 0, n - 1 } }); while (!q.empty()) { int m = q.size(); for ( int i = 0; i < m; i++) { auto p = q.front(); q.pop(); int leftEnd = mp[p.first->key] - 1; int rightStart = mp[p.first->key] + 1; // check if nodes to added into the left part of // q.front() if (p.second.first <= leftEnd) { p.first->left = new Node(levelOrder[idx++]); q.push({ p.first->left, { p.second.first, leftEnd } }); } // check if nodes to added into the right part // of q.front() if (rightStart <= p.second.second) { p.first->right = new Node(levelOrder[idx++]); q.push({ p.first->right, { rightStart, p.second.second } }); } } } return root; } |
Python3
class Node: def __init__( self , x): self .key = x self .left = None self .right = None def buildTree(inorder, levelOrder, iStart, iEnd, n): q = [] mp = {} for i in range (n): mp[inorder[i]] = i idx = 0 root = Node(levelOrder[idx]) idx + = 1 q.append((root, [ 0 , n - 1 ])) while len (q) ! = 0 : m = len (q) for i in range (m): node, [leftStart, rightEnd] = q.pop( 0 ) leftEnd = mp[node.key] - 1 rightStart = mp[node.key] + 1 if leftStart < = leftEnd: node.left = Node(levelOrder[idx]) idx + = 1 q.append((node.left, [leftStart, leftEnd])) if rightStart < = rightEnd: node.right = Node(levelOrder[idx]) idx + = 1 q.append((node.right, [rightStart, rightEnd])) return root def printInorder(node): if node is None : return printInorder(node.left) print (node.key, end = " " ) printInorder(node.right) n = 7 inOrder = [ 4 , 8 , 10 , 12 , 14 , 20 , 22 ] levelOrder = [ 20 , 8 , 22 , 4 , 12 , 10 , 14 ] root = None root = buildTree(inOrder, levelOrder, 0 , n - 1 , n) printInorder(root) |
C#
using System; using System.Collections.Generic; public class Node { public int key; public Node left; public Node right; public Node( int x) { key = x; left = null ; right = null ; } }; public class Gfg { public static Node buildTree( int [] inorder, int [] levelOrder, int iStart, int iEnd, int n) { Queue<Tuple<Node, Tuple< int , int >>> q = new Queue<Tuple<Node, Tuple< int , int >>>(); Dictionary< int , int > mp = new Dictionary< int , int >(); for ( int i = 0; i < n; i++) mp[inorder[i]] = i; int idx = 0; Node root = new Node(levelOrder[idx++]); q.Enqueue(Tuple.Create(root, Tuple.Create(0, n - 1))); while (q.Count > 0) { int m = q.Count; for ( int i = 0; i < m; i++) { var p = q.Dequeue(); int leftEnd = mp[p.Item1.key] - 1; int rightStart = mp[p.Item1.key] + 1; // check if nodes to added into the left part of // q.front() if (p.Item2.Item1 <= leftEnd) { p.Item1.left = new Node(levelOrder[idx++]); q.Enqueue(Tuple.Create(p.Item1.left, Tuple.Create(p.Item2.Item1, leftEnd))); } // check if nodes to added into the right part // of q.front() if (rightStart <= p.Item2.Item2) { p.Item1.right = new Node(levelOrder[idx++]); q.Enqueue(Tuple.Create(p.Item1.right, Tuple.Create(rightStart, p.Item2.Item2))); } } } return root; } public static void printInorder(Node node) { if (node == null ) return ; printInorder(node.left); Console.Write(node.key + " " ); printInorder(node.right); } public static void Main() { int n = 7; int [] inOrder = { 4, 8, 10, 12, 14, 20, 22 }; int [] levelOrder = { 20, 8, 22, 4, 12, 10, 14 }; Node root = buildTree(inOrder, levelOrder, 0, n - 1, n); printInorder(root); Console.WriteLine(); } } |
Javascript
// THIS CODE IS CONTRIBUTED BY CHANDAN AGARWAL class Node { constructor(x) { this .key = x; this .left = null ; this .right = null ; } } function buildTree(inorder, levelOrder, iStart, iEnd, n) { const q = []; const mp = new Map(); for (let i = 0; i < n; i++) { mp.set(inorder[i], i); } let idx = 0; const root = new Node(levelOrder[idx++]); q.push([root, [0, n - 1]]); while (q.length !== 0) { const m = q.length; for (let i = 0; i < m; i++) { const [node, [leftStart, rightEnd]] = q.shift(); const leftEnd = mp.get(node.key) - 1; const rightStart = mp.get(node.key) + 1; if (leftStart <= leftEnd) { node.left = new Node(levelOrder[idx++]); q.push([node.left, [leftStart, leftEnd]]); } if (rightStart <= rightEnd) { node.right = new Node(levelOrder[idx++]); q.push([node.right, [rightStart, rightEnd]]); } } } return root; } function printInorder(node) { if (node === null ) return ; printInorder(node.left); console.log(node.key + " " ); printInorder(node.right); } const n = 7; const inOrder = [4, 8, 10, 12, 14, 20, 22]; const levelOrder = [20, 8, 22, 4, 12, 10, 14]; let root = null ; root = buildTree(inOrder, levelOrder, 0, n - 1, n); printInorder(root); console.log( "" ); |
Java
// Java Program for the above approach import java.util.*; class Node { public int key; public Node left; public Node right; public Node( int x) { key = x; left = null ; right = null ; } } // Pair Class of Java class Pair<K, V> { private final K key; private final V value; public Pair(K key, V value) { this .key = key; this .value = value; } public K getKey() { return key; } public V getValue() { return value; } } class Gfg { public static Node buildTree( int [] inorder, int [] levelOrder, int iStart, int iEnd, int n) { Queue<Pair<Node, Pair<Integer, Integer>>> q = new LinkedList<>(); HashMap<Integer, Integer> mp = new HashMap<>(); for ( int i = 0 ; i < n; i++) mp.put(inorder[i], i); int idx = 0 ; Node root = new Node(levelOrder[idx++]); q.add( new Pair<>(root, new Pair<>( 0 , n - 1 ))); while (!q.isEmpty()) { int m = q.size(); for ( int i = 0 ; i < m; i++) { var p = q.poll(); int leftEnd = mp.get(p.getKey().key) - 1 ; int rightStart = mp.get(p.getKey().key) + 1 ; // check if nodes to added into the left part of // q.front() if (p.getValue().getKey() <= leftEnd) { p.getKey().left = new Node(levelOrder[idx++]); q.add( new Pair<>(p.getKey().left, new Pair<>(p.getValue().getKey(), leftEnd))); } // check if nodes to added into the right part // of q.front() if (rightStart <= p.getValue().getValue()) { p.getKey().right = new Node(levelOrder[idx++]); q.add( new Pair<>(p.getKey().right, new Pair<>(rightStart, p.getValue().getValue()))); } } } return root; } public static void printInorder(Node node) { if (node == null ) return ; printInorder(node.left); System.out.print(node.key + " " ); printInorder(node.right); } // Driver Code public static void main(String[] args) { int n = 7 ; int [] inOrder = { 4 , 8 , 10 , 12 , 14 , 20 , 22 }; int [] levelOrder = { 20 , 8 , 22 , 4 , 12 , 10 , 14 }; Node root = buildTree(inOrder, levelOrder, 0 , n - 1 , n); printInorder(root); System.out.println(); } } // This code is contributed by codebraxnzt |
4 8 10 12 14 20 22
Time complexity: O(N)
Auxiliary Space: O(N)
Please Login to comment...