Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

You will use the C++ code given below build a binary tree. You will write code to visit the tree in preorder, and levelorder. You

You will use the C++ code given below build a binary tree. You will write code to visit the tree in preorder, and levelorder. You should implement the stack using a large array, and the queue using a linked list. Use the code give as a start. The input should be 7, 3, 10, 2, 5, 8, 11, 4.

#include #include using namespace std; struct tnode { int item; tnode *left, *right; tnode(int Item, tnode *Left, tnode *Right) {item = Item; left = Left; right = Right;} }; void tprint(tnode *tptr) { if ( tptr ) { tprint( tptr->left ); cout << tptr->item << ; tprint( tptr->right ); } } struct snode { int counter; tnode * node; snode(int c = 0, tnode * n = 0) {counter = c; node = n;}

}; class stack { private: enum { STACK_SIZE = 128 }; snode _stack[STACK_SIZE]; int _top; public: stack() { _top = 0; } void push( snode ); snode pop(); snode top() { assert( _top > 0 ); return _stack[_top - 1]; } bool is_empty() { return !_top; } }; void stack::push( snode sval ) { assert( _top < STACK_SIZE ); _stack[_top++] = sval; } snode stack::pop() { assert( _top > 0 ); return _stack[--_top]; } tnode * buildTree(){ tnode *tree = 0, *prev, *curr, *trptr; int ival; cout << "> "; cin >> ival; while ( ival > 0 ) { tnode *tptr = new tnode(ival, 0, 0); if ( !tree ) { tree = tptr;

} else { curr = tree; while ( curr ) { prev = curr; if (ival < curr->item) curr = curr->left; else curr = curr->right; } if (ival < prev->item) prev->left = tptr; else prev->right = tptr; } cout << "> "; cin >> ival; } return tree; } void visit(tnode * t){ cout << t->item << " "; } int main() { tnode * tree = buildTree(); inorder(tree); cout << "---------------- "; levelorder(tree); }

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

Recommended Textbook for

Introduction To Data Mining

Authors: Pang Ning Tan, Michael Steinbach, Vipin Kumar

1st Edition

321321367, 978-0321321367

More Books

Students also viewed these Databases questions

Question

differentiate between intrinsic and extrinsic motivation

Answered: 1 week ago