- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Construct a complete binary tree from given array in level order fashion in C++
Suppose we have an array A[], with n elements. We have to construct the binary tree from the array in level order traversal. So the elements from the left in the array will be filled in the tree level-wise starting from level 0. So if the array is like A = [1, 2, 3, 4, 5, 6], then the tree will be like below:
If we see closer, we can find that when the parent is present at index i, then its two children will be at index (2i + 1), and (2i + 2). Thus we can insert left and right nodes using its parent nodes. The first element of the array will be the root of the tree.
Example
#include <iostream> using namespace std; class Node { public: int data; Node* left, * right; }; Node* getNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return node; } Node* insertLevelWise(int arr[], Node* root, int i, int n) { if (i < n) { Node* temp = getNode(arr[i]); root = temp; root->left = insertLevelWise(arr, root->left, 2 * i + 1, n); root->right = insertLevelWise(arr, root->right, 2 * i + 2, n); } return root; } void inorderTrav(Node* root) { if (root != NULL){ inorderTrav(root->left); cout << root->data <<" "; inorderTrav(root->right); } } int main() { int arr[] = { 1, 2, 3, 4, 5, 6}; int n = sizeof(arr)/sizeof(arr[0]); Node* root = insertLevelWise(arr, root, 0, n); cout << "Inorder traversal of created tree: "; inorderTrav(root); }
Output
Inorder traversal of created tree: 4 2 5 1 6 3
- Related Articles
- Binary Tree Level Order Traversal in C++
- Construct BST from its given level order traversal in C++
- Construct Special Binary Tree from given Inorder traversal in C++
- Construct a Binary Search Tree from given postorder in Python
- Construct Binary Tree from String in C++
- Binary Tree Zigzag Level Order Traversal in Python
- Program to perform level order traversal of binary tree in C++
- Find the largest Complete Subtree in a given Binary Tree in C++
- Construct String from Binary Tree in Python
- Complete Binary Tree Inserter in C++
- Create a mirror tree from the given binary tree in C++ Program
- Maximum Level Sum of a Binary Tree in C++
- Construct a Binary Tree from Postorder and Inorder in Python
- Find the largest Complete Subtree in a given Binary Tree in Python
- Construct Binary Search Tree from Preorder Traversal in Python

Advertisements