Complete binary tree from array in level order fashion.

Complete binary tree from array in level order fashion. elements from left in the array will be filled in the tree level wise starting from level 0 and 3rd Sem Data Structure and Application lab 7th program

Given an array of elements, construct a complete binary tree from this array in level order fashion. That is, elements from left in the array will be filled in the tree level wise starting from level 0. Ex: Input :
arr[] = {1, 2, 3, 4, 5, 6}
Output : Root of the following tree
1
/ \

2 3
/ \ / \
4 5 6

/* Given an array of elements, construct a complete binary tree from this array in level order fashion. That is, elements from left in the array will be filled in the tree level wise starting from level 0. Ex: Input :
arr[] = {1, 2, 3, 4, 5, 6}
Output : Root of the following tree
1
/ \
2 3
/ \ /\
4 5 6 */

#include <stdio.h>
#include <stdlib.h>

struct Node {
  int data;
  struct Node* left;
  struct Node* right;
};

struct Node* createNode(int data) {
  struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
  newNode->data = data;
  newNode->left = NULL;
  newNode->right = NULL;
  return newNode;
}

int i = 0;

struct Node* constructTreeFromArray(int* arr, int n) {
  if (i >= n) {
    return NULL;
  }
  struct Node* root = createNode(arr[i++]);
  root->left = constructTreeFromArray(arr, n);
  root->right = constructTreeFromArray(arr, n);
  return root;
}

void levelOrderTraversal(struct Node* root) {
  if (root == NULL) {
    return;
  }
  printf("%d ", root->data);
  levelOrderTraversal(root->left);
  levelOrderTraversal(root->right);
}

int main() {
  int arr[] = {1, 2, 3, 4, 5, 6};
  int n = sizeof(arr) / sizeof(arr[0]);
  struct Node* root = constructTreeFromArray(arr, n);
  levelOrderTraversal(root);
  return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *