79.1k views
3 votes
the size field now has the number of elements for the trees array of the class tree. a null reference to this array has already been declared at the class level. it is time to give the trees array dimension.

User Ashok Goli
by
6.8k points

1 Answer

2 votes

C++ : // 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[],

int i, int n)

{

Node *root = nullptr;

// Base case for recursion

if (i < n)

{

root = newNode(arr[i]);

// insert left child

root->left = insertLevelOrder(arr,

2 * i + 1, n);

// insert right child

root->right = insertLevelOrder(arr,

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, 0, n);

inOrder(root);

}

User JonF
by
7.9k points

No related questions found

Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.

9.4m questions

12.2m answers

Categories