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 #include #include #include 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 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(" "); tree->preorder(); printf(" "); tree->postorder(); printf(" "); tree->levelorder(); printf(" "); }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

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

Step: 3

blur-text-image

Ace Your Homework with AI

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

Get Started

Students also viewed these Databases questions

Question

Identify the different methods employed in the selection process.

Answered: 1 week ago

Question

Demonstrate the difference between ability and personality tests.

Answered: 1 week ago