The Wayback Machine - https://web.archive.org/web/20241217070517/https://www.geeksforgeeks.org/construct-tree-from-given-inorder-and-preorder-traversal/
Open In App

Construct Tree from given Inorder and Preorder traversals

Last Updated : 30 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given in-order and pre-order traversals of a Binary Tree, the task is to construct the Binary Tree and return its root.

Example:

Input: inorder[] = [3 1 4 0 5 2], preorder[] = [0 1 3 4 2 5]
Output: 3 4 1 5 2 0
Explanation: The tree will look like:

construct-tree-from-given-inorder-and-preorder-traversals

[Naive Approach] Using Pre-order traversal – O(n^2) Time and O(h) Space

The idea is to construct the tree using pre-order traversal. Take the first element of the pre-order array and create root node. Find the index of this node in the in-order array. Create the left subtree using the elements present on left side of root node in in-order array. Similarly create the right subtree using the elements present on the right side of the root node in in-order array.

Below is the implementation of the above approach:

C++
// c++ program to construct tree using 
// inorder and preorder traversals
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node *left, *right;
    Node(int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// Function to find the index of an element.
int searchValue(vector<int>& in, int value, int s, int e) {
    
    for (int i=s; i<=e; i++) {
        if (in[i] == value)
            return i;
    }
    return -1;
}

// Recursive function to build the binary tree.
Node* buildTreeRecur(vector<int>& in, vector<int>& pre, 
                     int &preIndex, int s, int e) {
    
    // For empty array, return null
    if (s > e) return nullptr;
    
    // create the root Node
    Node* root = new Node(pre[preIndex]);
    preIndex++;
    
    // find the index of first element of pre-order array
    // in the in-order array.
    int index = searchValue(in, pre[preIndex-1], s, e);
    
    // Recursively create the left and right subtree.
    root->left = buildTreeRecur(in, pre, preIndex, s, index-1);
    root->right = buildTreeRecur(in, pre, preIndex, index+1, e);
    
    return root;
}

Node* buildTree(vector<int>& in, vector<int>& pre) {
    
    // Build the tree recursively.
      int n = pre.size();
    int preIndex = 0;
    Node* root = buildTreeRecur(in, pre, preIndex, 0, n-1);
    
    return root;
}

void printPostorder(Node* root) {
    if (root == nullptr)
        return;
    printPostorder(root->left);
    printPostorder(root->right);
    cout << root->data << " ";
}

int main() {
    vector<int> in = {3, 1, 4, 0, 5, 2};
    vector<int> pre = {0, 1, 3, 4, 2, 5};
    Node* root = buildTree(in, pre);

    printPostorder(root);

    return 0;
}
Java
// Java program to construct tree using 
// inorder and preorder traversals
class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Function to find the index of an element.
    static int searchValue(int[] in, int value, int s, int e) {
        for (int i = s; i <= e; i++) {
            if (in[i] == value)
                return i;
        }
        return -1;
    }

    // Recursive function to build the binary tree.
    static Node buildTreeRecur(int[] in, int[] pre, 
                               int[] preIndex, int s, int e) {
        
        // For empty array, return null
        if (s > e) return null;

        // create the root Node
        Node root = new Node(pre[preIndex[0]]);
        preIndex[0]++;
        
        // find the index of first element of pre-order array
        // in the in-order array.
        int index = searchValue(in, pre[preIndex[0] - 1], s, e);

        // Recursively create the left and right subtree.
        root.left = buildTreeRecur(in, pre, preIndex, s, index - 1);
        root.right = buildTreeRecur(in, pre, preIndex, index + 1, e);

        return root;
    }

    static Node buildTree(int[] in, int[] pre) {
        int n = in.length;
        
        // Build the tree recursively.
        int[] preIndex = {0};
        return buildTreeRecur(in, pre, preIndex, 0, n - 1);
    }

    static void printPostorder(Node root) {
        if (root == null) return;
        printPostorder(root.left);
        printPostorder(root.right);
        System.out.print(root.data + " ");
    }

    public static void main(String[] args) {
        int[] in = {3, 1, 4, 0, 5, 2};
        int[] pre = {0, 1, 3, 4, 2, 5};
        Node root = buildTree(in, pre);

        printPostorder(root);
    }
}
Python
# Python program to construct tree using 
# inorder and preorder traversals

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Function to find the index of an element.
def searchValue(inorder, value, s, e):
    for i in range(s, e + 1):
        if inorder[i] == value:
            return i
    return -1

# Recursive function to build the binary tree.
def buildTreeRecur(inorder, preorder, preIndex, s, e):
    
    # For empty array, return None
    if s > e:
        return None

    # create the root Node
    root = Node(preorder[preIndex[0]])
    preIndex[0] += 1

    # find the index of first element of pre-order array
    # in the in-order array.
    index = searchValue(inorder, preorder[preIndex[0] - 1], s, e)

    # Recursively create the left and right subtree.
    root.left = buildTreeRecur(inorder, preorder, \
                               preIndex, s, index - 1)
    root.right = buildTreeRecur(inorder, preorder, \
                                preIndex, index + 1, e)

    return root

def buildTree(inorder, preorder):
    n = len(inorder)
    
    # Build the tree recursively.
    preIndex = [0]
    return buildTreeRecur(inorder, preorder,\
                          preIndex, 0, n - 1)

def printPostorder(root):
    if root is None:
        return
    printPostorder(root.left)
    printPostorder(root.right)
    print(root.data, end=" ")

inorder = [3, 1, 4, 0, 5, 2]
preorder = [0, 1, 3, 4, 2, 5]
root = buildTree(inorder, preorder)

printPostorder(root)
C#
// C# program to construct tree using 
// inorder and preorder traversals
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Function to find the index of an element.
    static int SearchValue(List<int> inorder, 
                           int value, int s, int e) {
        for (int i = s; i <= e; i++) {
            if (inorder[i] == value)
                return i;
        }
        return -1;
    }

    // Recursive function to build the binary tree.
    static Node BuildTreeRecur(List<int> inorder, 
    List<int> preorder, ref int preIndex, int s, int e) {
        
        // For empty array, return null
        if (s > e) return null;

        // create the root Node
        Node root = new Node(preorder[preIndex]);
        preIndex++;

        // find the index of first element of pre-order array
        // in the in-order array.
        int index = SearchValue(inorder, 
                                preorder[preIndex - 1], s, e);

        // Recursively create the left and right subtree.
        root.left = BuildTreeRecur
           (inorder, preorder, ref preIndex, s, index - 1);
        root.right = BuildTreeRecur
        (inorder, preorder, ref preIndex, index + 1, e);

        return root;
    }

    static Node BuildTree(List<int> inorder, 
                          List<int> preorder) {
        int n = inorder.Count;
        
        // Build the tree recursively.
        int preIndex = 0;
        return BuildTreeRecur(inorder, preorder, 
                              ref preIndex, 0, n - 1);
    }

    static void PrintPostorder(Node root) {
        if (root == null) return;
        PrintPostorder(root.left);
        PrintPostorder(root.right);
        Console.Write(root.data + " ");
    }

    static void Main(string[] args) {

        List<int> inorder = new List<int> { 3, 1, 4, 0, 5, 2 };
        List<int> preorder = new List<int> { 0, 1, 3, 4, 2, 5 };
        Node root = BuildTree(inorder, preorder);

        PrintPostorder(root);
    }
}
JavaScript
// JavaScript program to construct tree using 
// inorder and preorder traversals

class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Function to find the index of an element.
function searchValue(inorder, value, s, e) {
    for (let i = s; i <= e; i++) {
        if (inorder[i] === value) return i;
    }
    return -1;
}

// Recursive function to build the binary tree.
function buildTreeRecur(inorder, preorder, preIndex, s, e) {
    
    // For empty array, return null
    if (s > e) return null;

    // create the root Node
    let root = new Node(preorder[preIndex[0]]);
    preIndex[0]++;

    // find the index of first element of pre-order array
    // in the in-order array.
    let index = searchValue(inorder, 
                            preorder[preIndex[0] - 1], s, e);

    // Recursively create the left and right subtree.
    root.left = buildTreeRecur(inorder, preorder,
                                preIndex, s, index - 1);
    root.right = buildTreeRecur(inorder, preorder, 
                                preIndex, index + 1, e);

    return root;
}

function buildTree(inorder, preorder) {
    const n = inorder.length;
    
    // Build the tree recursively.
    let preIndex = [0];
    return buildTreeRecur(inorder, preorder,
                          preIndex, 0, n - 1);
}

function printPostorder(root) {
    if (root === null) return;
    printPostorder(root.left);
    printPostorder(root.right);
    console.log(root.data);
}

const inorder = [3, 1, 4, 0, 5, 2];
const preorder = [0, 1, 3, 4, 2, 5];
const root = buildTree(inorder, preorder);

printPostorder(root);

Output
3 4 1 5 2 0 

[Expected Approach] Using Pre-order traversal and Hash map – O(n) Time and O(n) Space

The idea is similar to first approach, but instead of linearly searching the in-order array for each node we can use hashing. Map the values of in-order array to its indices. This will reduce the searching complexity from O(n) to O(1).

Below is the implementation of the above approach:

C++
// c++ program to construct tree using 
// inorder and preorder traversals
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node *left, *right;
    Node(int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// Recursive function to build the binary tree.
Node* buildTreeRecur(unordered_map<int,int> &mp, vector<int>& pre, 
                     int &preIndex, int s, int e) {
    
    // For empty array, return null
    if (s>e) return nullptr;
    
    // create the root Node
    Node* root = new Node(pre[preIndex]);
    preIndex++;
    
    // find the index of first element of pre-order array
    // in the in-order array.
    int index = mp[pre[preIndex-1]];
    
    // Recursively create the left and right subtree.
    root->left = buildTreeRecur(mp, pre, preIndex, s, index-1);
    root->right = buildTreeRecur(mp, pre, preIndex, index+1, e);
    
    return root;
}

Node* buildTree(vector<int>& in, vector<int>& pre) {
    
    // Build the tree recursively.
    int preIndex = 0;
      int n = pre.size();
    
    // Map the values to their indices
    unordered_map<int,int> mp;
    for (int i=0; i<n; i++) {
        mp[in[i]] = i;
    }
    Node* root = buildTreeRecur
                      (mp, pre, preIndex, 0, n-1);
    
    return root;
}

void printPostorder(Node* root) {
    if (root == nullptr)
        return;
    printPostorder(root->left);
    printPostorder(root->right);
    cout << root->data << " ";
}

int main() {
  
    vector<int> in = {3, 1, 4, 0, 5, 2};
    vector<int> pre = {0, 1, 3, 4, 2, 5};
    Node* root = buildTree(in, pre);

    printPostorder(root);

    return 0;
}
Java
// Java program to construct tree using 
// inorder and preorder traversals

import java.util.HashMap;

class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Recursive function to build the binary tree.
    static Node buildTreeRecur(HashMap<Integer, Integer> map,
    int[] pre, int[] preIndex, int s, int e) {
        
        // For empty array, return null
        if (s > e) return null;
        
        // create the root Node
        Node root = new Node(pre[preIndex[0]]);
        preIndex[0]++;
        
        // find the index of first element of pre-order array
        // in the in-order array.
        int index = map.get(pre[preIndex[0] - 1]);
        
        // Recursively create the left and right subtree.
        root.left = buildTreeRecur(map, pre, preIndex, s, index - 1);
        root.right = buildTreeRecur(map, pre, preIndex, index + 1, e);
        
        return root;
    }

    static Node buildTree(int[] in, int[] pre) {
        int n = in.length;
        
        // Build the tree recursively.
        int[] preIndex = {0};
        
        // Map the values to their indices
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < n; i++) {
            map.put(in[i], i);
        }
        return buildTreeRecur(map, pre, preIndex, 0, n - 1);
    }

    static void printPostorder(Node root) {
        if (root == null)
            return;
        printPostorder(root.left);
        printPostorder(root.right);
        System.out.print(root.data + " ");
    }

    public static void main(String[] args) {
        int[] in = {3, 1, 4, 0, 5, 2};
        int[] pre = {0, 1, 3, 4, 2, 5};
        Node root = buildTree(in, pre);

        printPostorder(root);
    }
}
Python
# Python program to construct tree using 
# inorder and preorder traversals

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Recursive function to build the binary tree.
def buildTreeRecur(map, pre, preIndex, s, e):
    
    # For empty array, return None
    if s > e:
        return None

    # create the root Node
    root = Node(pre[preIndex[0]])
    preIndex[0] += 1

    # find the index of first element of pre-order array
    # in the in-order array.
    index = map[pre[preIndex[0] - 1]]

    # Recursively create the left and right subtree.
    root.left = buildTreeRecur(map, pre, preIndex, s, index - 1)
    root.right = buildTreeRecur(map, pre, preIndex, index + 1, e)

    return root

def buildTree(inorder, preorder):
    n = len(inorder)
    
    # Build the tree recursively.
    preIndex = [0]
    
    # Map the values to their indices
    map = {inorder[i]: i for i in range(n)}
    return buildTreeRecur(map, preorder, preIndex, 0, n - 1)

def printPostorder(root):
    if root is None:
        return
    printPostorder(root.left)
    printPostorder(root.right)
    print(root.data, end=" ")

inorder = [3, 1, 4, 0, 5, 2]
preorder = [0, 1, 3, 4, 2, 5]
root = buildTree(inorder, preorder)

printPostorder(root)
C#
// C# program to construct tree using 
// inorder and preorder traversals

using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Recursive function to build the binary tree.
    static Node BuildTreeRecur(Dictionary<int, int> map, 
    List<int> pre, ref int preIndex, int s, int e) {
        
        // For empty array, return null
        if (s > e) return null;

        // create the root Node
        Node root = new Node(pre[preIndex]);
        preIndex++;

        // find the index of first element of pre-order array
        // in the in-order array.
        int index = map[pre[preIndex - 1]];

        // Recursively create the left and 
          // right subtree.
        root.left = BuildTreeRecur(map, pre, 
                                   ref preIndex, s, index - 1);
        root.right = BuildTreeRecur(map, pre, 
                                    ref preIndex, index + 1, e);

        return root;
    }

    static Node BuildTree(List<int> inorder,
                          List<int> preorder) {
        int n = inorder.Count;
        
        // Build the tree recursively.
        int preIndex = 0;

        // Map the values to their indices
        Dictionary<int, int> map = new Dictionary<int, int>();
        for (int i = 0; i < n; i++) {
            map[inorder[i]] = i;
        }
        return BuildTreeRecur(map, preorder, 
                              ref preIndex, 0, n - 1);
    }

    static void PrintPostorder(Node root) {
        if (root == null)
            return;
        PrintPostorder(root.left);
        PrintPostorder(root.right);
        Console.Write(root.data + " ");
    }

    static void Main() {
        List<int> inorder = new List<int> { 3, 1, 4, 0, 5, 2 };
        List<int> preorder = new List<int> { 0, 1, 3, 4, 2, 5 };
        
        Node root = BuildTree(inorder, preorder);

        PrintPostorder(root);
    }
}
JavaScript
// JavaScript program to construct tree using 
// inorder and preorder traversals

class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Recursive function to build the binary tree.
function buildTreeRecur(map, pre, preIndex, s, e) {
    
    // For empty array, return null
    if (s > e) return null;

    // create the root Node
    let root = new Node(pre[preIndex[0]]);
    preIndex[0]++;

    // find the index of first element of pre-order array
    // in the in-order array.
    let index = map.get(pre[preIndex[0] - 1]);

    // Recursively create the left and right subtree.
    root.left = buildTreeRecur(map, pre, preIndex, s, index - 1);
    root.right = buildTreeRecur(map, pre, preIndex, index + 1, e);

    return root;
}

function buildTree(inorder, preorder) {
    let n = inorder.length;
    
    // Build the tree recursively.
    let preIndex = [0];

    // Map the values to their indices
    let map = new Map();
    for (let i = 0; i < n; i++) {
        map.set(inorder[i], i);
    }
    return buildTreeRecur(map, preorder, preIndex, 0, n - 1);
}

function printPostorder(root) {
    if (root === null)
        return;
    printPostorder(root.left);
    printPostorder(root.right);
    console.log(root.data);
}

let inorder = [3, 1, 4, 0, 5, 2];
let preorder = [0, 1, 3, 4, 2, 5];
let root = buildTree(inorder, preorder);

printPostorder(root);

Output
3 4 1 5 2 0 

Related articles:



Next Article

Similar Reads

three90RightbarBannerImg