Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Using C++, add comments to explain the following code: #include #include #include #include using namespace std; int flag; class Tree { public: Tree() { int

Using C++, add comments to explain the following code:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <queue>
using namespace std;

int flag;
class Tree
{
public:
Tree()
{
int j;
for (j = 0; j < 2000; j++)
root[j] = -1;
}
void insert(int node)
{
int index = 0;
while (index < 2000 && root[index] != -1)
{
if (root[index] < node) // index*2 +1 : left node, +2 : right node.
index = index * 2 + 2;
else
index = index * 2 + 1;
}
root[index] = node;
}
void inorder()
{
flag = 0;
inorder(0);
}
void inorder(int idx)
{
if (root[idx * 2 + 1] != -1)
inorder(idx * 2 + 1);
if (flag == 1)
cout << ",";
flag = 1;
cout << root[idx];
if (root[idx * 2 + 2] != -1)
inorder(idx * 2 + 2);
}
void preorder()
{
flag = 0;
inorder(0);
}
void preorder(int idx)
{
if (flag == 1)
cout << ",";
flag = 1;
cout << root[idx];
if (root[idx * 2 + 1] != -1)
preorder(idx * 2 + 1);
if (root[idx * 2 + 2] != -1)
preorder(idx * 2 + 2);
}
void postorder()
{
flag = 0;
inorder(0);
}
void postorder(int idx)
{
if (root[idx * 2 + 1] != -1)
postorder(idx * 2 + 1);
if (root[idx * 2 + 2] != -1)
postorder(idx * 2 + 2);
if (flag == 1)
cout << ",";
flag = 1;
cout << root[idx];
}
void levelorder()
{
flag = 0;
queue<int> list;
int idx = 0;
list.push(0);
while (!list.empty())
{
if (flag == 1)
cout << ",";
flag = 1;
idx = list.front();
cout << root[idx];
if (root[idx * 2 + 1] != -1)
list.push(idx * 2 + 1);
if (root[idx * 2 + 2] != -1)
list.push(idx * 2 + 2);
list.pop();
}
}

private:
int root[2000];
};

int main()
{
Tree *tree = new Tree();
int j, node;
srand(time(NULL));
for (j = 0; j < 10; j++)
{
node = rand();
tree->insert(node);
}
tree->inorder();
printf("n");
tree->preorder();
printf("n");
tree->postorder();
printf("n");
tree->levelorder();
printf("n");
}

Step by Step Solution

3.44 Rating (160 Votes )

There are 3 Steps involved in it

Step: 1

Comment and code explanation This is a C program that creates a tree data structure and performs sev... blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

C++ Primer Plus

Authors: Stephen Prata

6th Edition

978-0321776402, 0321776402

More Books

Students also viewed these Programming questions

Question

How do you appeal to manifest motives? Latent motives?

Answered: 1 week ago

Question

please dont use chat gpt or other AI 8 0 5 . .

Answered: 1 week ago