Question
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
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
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
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started