Computer Science, asked by swaroopsreepuram2611, 2 months ago

cod for construction of binary tree​

Answers

Answered by NivedidhaS
0

Answer:

first make me brainleast

Explanation:

Given an array of elements, our task is to 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.

Examples:

Input : arr[] = {1, 2, 3, 4, 5, 6}

Output : Root of the following tree

1

/ \

2 3

/ \ /

4 5 6

Input: arr[] = {1, 2, 3, 4, 5, 6, 6, 6, 6, 6}

Output: Root of the following tree

1

/ \

2 3

/ \ / \

4 5 6 6

/ \ /

6 6 6

If we observe carefully we can see that if parent node is at index i in the array then the left child of that node is at index (2*i + 1) and right child is at index (2*i + 2) in the array.

Using this concept, we can easily insert the left and right nodes by choosing its parent node. We will insert the first element present in the array as the root node at level 0 in the tree and start traversing the array and for every node i we will insert its both childs left and right in the tree.

Below is the recursive program to do this:

// CPP program to construct binary

// tree from given array in level

// order fashion Tree Node

#include <bits/stdc++.h>

using namespace std;

/* A binary tree node has data,

pointer to left child and a

pointer to right child */

struct Node

{

int data;

Node* left, * right;

};

/* Helper function that allocates a

new node */

Node* newNode(int data)

{

Node* node = (Node*)malloc(sizeof(Node));

node->data = data;

node->left = node->right = NULL;

return (node);

}

// Function to insert nodes in level order

Node* insertLevelOrder(int arr[], Node* root,

int i, int n)

{

// Base case for recursion

if (i < n)

{

Node* temp = newNode(arr[i]);

root = temp;

// insert left child

root->left = insertLevelOrder(arr,

root->left, 2 * i + 1, n);

// insert right child

root->right = insertLevelOrder(arr,

root->right, 2 * i + 2, n);

}

return root;

}

// Function to print tree nodes in

// InOrder fashion

void inOrder(Node* root)

{

if (root != NULL)

{

inOrder(root->left);

cout << root->data <<" ";

inOrder(root->right);

}

}

// Driver program to test above function

int main()

{

int arr[] = { 1, 2, 3, 4, 5, 6, 6, 6, 6 };

int n = sizeof(arr)/sizeof(arr[0]);

Node* root = insertLevelOrder(arr, root, 0, n);

inOrder(root);

}

Answered by cgDarshan
0

do LCM

Explanation:

then do like this

that is binary code

Attachments:
Similar questions