Construct Full Binary Tree from given preorder and postorder traversals
Last Updated :
23 Jul, 2025
Given two arrays that represent preorder and postorder traversals of a full binary tree, construct the binary tree. Full Binary Tree is a binary tree where every node has either 0 or 2 children.
Examples of Full Trees.
Input: pre[] = [1, 2, 4, 8, 9, 5, 3, 6, 7] , post[] = [8, 9, 4, 5, 2, 6, 7, 3, 1]
Output:
Input: pre[] = [1, 2, 4, 5, 3, 6, 7] , post[] = [4, 5, 2, 6, 7, 3, 1]
Output:
It is not possible to construct a general Binary Tree from preorder and postorder traversals (Please refer to If you are given two traversal sequences, can you construct the binary tree?). But if you know that the Binary Tree is Full, we can construct the tree without ambiguity.
Let us consider the two given arrays as pre[] = {1, 2, 4, 8, 9, 5, 3, 6, 7} and post[] = {8, 9, 4, 5, 2, 6, 7, 3, 1};
In pre[], the leftmost element is root of tree. Since the tree is full and array size is more than 1. The value next to 1 in pre[], must be left child of root. So we know 1 is root and 2 is left child. How to find the all nodes in left subtree? We know 2 is root of all nodes in left subtree. All nodes before 2 in post[] must be in left subtree. Now we know 1 is root, elements {8, 9, 4, 5, 2} are in left subtree, and the elements {6, 7, 3} are in right subtree.
We recursively follow the above approach and get the following tree.
C++
// C++ code for construction of full binary tree
#include <bits/stdc++.h>
#include <vector>
using namespace std;
class Node {
public:
int data;
Node *left;
Node *right;
Node(int x) {
data = x;
left = right = nullptr;
}
};
// A recursive function to construct Full from pre[] and post[].
// preIndex is used to keep track of index in pre[].
// l is low index and h is high index for the current
// subarray in post[]
Node* constructTreeUtil (vector<int> &pre, vector<int> &post, int &preIndex,
int l, int h, int size) {
if (preIndex >= size || l > h)
return nullptr;
// The first node in preorder traversal is root.
// So take the node at preIndex from preorder and make it root,
// and increment preIndex
Node* root = new Node(pre[preIndex]);
++preIndex;
// If the current subarray has only one element,
// no need to recur
if (l == h)
return root;
// Search the next element of pre[] in post[]
int i;
for (i = l; i <= h; ++i)
if (pre[preIndex] == post[i])
break;
// Use the index of element found in
// postorder to divide postorder array in two parts:
// left subtree and right subtree
if (i <= h) {
root->left = constructTreeUtil(pre, post,
preIndex, l, i, size);
root->right = constructTreeUtil(pre, post,
preIndex, i + 1, h - 1, size);
}
return root;
}
// The main function to construct Full Binary Tree from given preorder and
// postorder traversals. This function mainly uses constructTreeUtil()
Node *constructTree (vector<int> &pre, vector<int> &post) {
int preIndex = 0;
int size = pre.size();
return constructTreeUtil(pre, post, preIndex,
0, size - 1, size);
}
// A utility function to print inorder
// traversal of a Binary Tree
void print (Node* curr) {
if (curr == nullptr)
return;
print(curr->left);
printf("%d ", curr->data);
print(curr->right);
}
int main () {
vector<int> pre = {1, 2, 4, 8, 9, 5, 3, 6, 7};
vector<int> post = {8, 9, 4, 5, 2, 6, 7, 3, 1};
Node *root = constructTree(pre, post);
print(root);
return 0;
}
Java
// Java code for construction of full binary tree
// from given preorder and postorder traversals
import java.util.Arrays;
import java.util.List;
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// A recursive function to construct Full from pre[] and
// post[]. preIndex is used to keep track of index in
// pre[]. l is low index and h is high index for the
// current subarray in post[]
static Node constructTreeUtil(List<Integer> pre,
List<Integer> post,
int[] preIndex, int l,
int h, int size) {
if (preIndex[0] >= size || l > h)
return null;
// The first node in preorder traversal is root.
// So take the node at preIndex from preorder and
// make it root, and increment preIndex
Node root = new Node(pre.get(preIndex[0]));
preIndex[0]++;
// If the current subarray has only one
// element, no need to recur
if (l == h)
return root;
// Search the next element of pre[] in post[]
int i;
for (i = l; i <= h; ++i)
if (pre.get(preIndex[0]) == post.get(i))
break;
// Use the index of element found in
// postorder to divide postorder array in two parts:
// left subtree and right subtree
if (i <= h) {
root.left = constructTreeUtil(
pre, post, preIndex, l, i, size);
root.right = constructTreeUtil(
pre, post, preIndex, i + 1, h - 1, size);
}
return root;
}
// The main function to construct Full Binary Tree from
// given preorder and postorder traversals. This
// function mainly uses constructTreeUtil()
static Node constructTree(List<Integer> pre,
List<Integer> post) {
int[] preIndex = { 0 };
int size = pre.size();
return constructTreeUtil(pre, post, preIndex, 0,
size - 1, size);
}
// A utility function to print inorder traversal of a
// Binary Tree
static void print(Node curr) {
if (curr == null)
return;
print(curr.left);
System.out.print(curr.data + " ");
print(curr.right);
}
public static void main(String[] args) {
List<Integer> pre
= Arrays.asList(1, 2, 4, 8, 9, 5, 3, 6, 7);
List<Integer> post
= Arrays.asList(8, 9, 4, 5, 2, 6, 7, 3, 1);
Node root = constructTree(pre, post);
print(root);
}
}
Python
# Python3 program for construction of
# full binary tree
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
def construct_tree_util(pre, post, pre_index, l, h):
if pre_index[0] >= len(pre) or l > h:
return None
# The first node in preorder traversal is root
root = Node(pre[pre_index[0]])
pre_index[0] += 1
# If the current subarray has only one element,
# no need to recur
if l == h:
return root
# Search the next element of pre[] in post[]
i = 0
for i in range(l, h + 1):
if pre[pre_index[0]] == post[i]:
break
# Use the index found in postorder to
# divide into left and right subtrees
if i <= h:
root.left = construct_tree_util\
(pre, post, pre_index, l, i)
root.right = construct_tree_util\
(pre, post, pre_index, i + 1, h - 1)
return root
def construct_tree(pre, post):
pre_index = [0]
return construct_tree_util\
(pre, post, pre_index, 0, len(post) - 1)
def print_inorder(node):
if node is None:
return
print_inorder(node.left)
print(node.data, end=' ')
print_inorder(node.right)
if __name__ == "__main__":
pre = [1, 2, 4, 8, 9, 5, 3, 6, 7]
post = [8, 9, 4, 5, 2, 6, 7, 3, 1]
root = construct_tree(pre, post)
print_inorder(root)
print()
C#
// C# code for construction of full binary
// tree from given preorder and postorder traversals
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// A recursive function to construct Full from pre[] and
// post[]. preIndex is used to keep track of index in
// pre[]. l is low index and h is high index for the
// current subarray in post[]
static Node ConstructTreeUtil(List<int> pre,
List<int> post,
ref int preIndex, int l,
int h, int size) {
if (preIndex >= size || l > h)
return null;
// The first node in preorder traversal is root. So
// take the node at preIndex from preorder and make
// it root, and increment preIndex
Node root = new Node(pre[preIndex]);
preIndex++;
// If the current subarray has only one element, no
// need to recur
if (l == h)
return root;
// Search the next element of pre[] in post[]
int i;
for (i = l; i <= h; ++i)
if (pre[preIndex] == post[i])
break;
// Use the index of element found in postorder to
// divide postorder array in two parts: left subtree
// and right subtree
if (i <= h) {
root.left = ConstructTreeUtil(
pre, post, ref preIndex, l, i, size);
root.right
= ConstructTreeUtil(pre, post, ref preIndex,
i + 1, h - 1, size);
}
return root;
}
// The main function to construct Full Binary Tree from
// given preorder and postorder traversals. This
// function mainly uses constructTreeUtil()
static Node ConstructTree(List<int> pre,
List<int> post) {
int preIndex = 0;
int size = pre.Count;
return ConstructTreeUtil(pre, post, ref preIndex, 0,
size - 1, size);
}
// A utility function to print inorder traversal of a
// Binary Tree
static void Print(Node curr) {
if (curr == null)
return;
Print(curr.left);
Console.Write(curr.data + " ");
Print(curr.right);
}
static void Main(string[] args) {
List<int> pre
= new List<int>{ 1, 2, 4, 8, 9, 5, 3, 6, 7 };
List<int> post
= new List<int>{ 8, 9, 4, 5, 2, 6, 7, 3, 1 };
Node root = ConstructTree(pre, post);
Print(root);
}
}
JavaScript
// Javascript code for construction of full binary tree
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
function constructTreeUtil(pre, post, preIndex, l, h) {
if (preIndex[0] >= pre.length || l > h) {
return null;
}
// The first node in preorder traversal is root
const root = new Node(pre[preIndex[0]]);
preIndex[0]++;
// If the current subarray has only one element, no need
// to recur
if (l === h) {
return root;
}
// Search the next element of pre[] in post[]
let i;
for (i = l; i <= h; i++) {
if (pre[preIndex[0]] === post[i]) {
break;
}
}
// Use the index found in postorder to
// divide into left and right subtrees
if (i <= h) {
root.left
= constructTreeUtil(pre, post, preIndex, l, i);
root.right = constructTreeUtil(pre, post, preIndex,
i + 1, h - 1);
}
return root;
}
function constructTree(pre, post) {
const preIndex = [ 0 ];
return constructTreeUtil(pre, post, preIndex, 0,
post.length - 1);
}
function printInorder(node) {
if (node === null) {
return;
}
printInorder(node.left);
console.log(node.data + " ");
printInorder(node.right);
}
const pre = [ 1, 2, 4, 8, 9, 5, 3, 6, 7 ];
const post = [ 8, 9, 4, 5, 2, 6, 7, 3, 1 ];
const root = constructTree(pre, post);
printInorder(root);
console.log();
Time Complexity: O(h), where h is height of tree.
Auxiliary Space: O(h)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem