Write a C++ function that takes a binary search tree as input and produces a lin
ID: 3681733 • Letter: W
Question
Write a C++ function that takes a binary search tree as input and produces a linked list of the entries, with the entries sorted (smallest entries at the front of the list and largest entries at the back). Hint: use in-order traversal. Also, create a test program.
Explanation / Answer
#include using namespace std; // Node class class Node { int key; Node* left; Node* right; public: Node() { key=-1; left=NULL; right=NULL; }; void setKey(int aKey) { key = aKey; }; void setLeft(Node* aLeft) { left = aLeft; }; void setRight(Node* aRight) { right = aRight; }; int Key() { return key; }; Node* Left() { return left; }; Node* Right() { return right; }; }; // Tree class class Tree { Node* root; public: Tree(); ~Tree(); Node* Root() { return root; }; void addNode(int key); void inOrder(Node* n); void preOrder(Node* n); void postOrder(Node* n); private: void addNode(int key, Node* leaf); void freeNode(Node* leaf); }; // Constructor Tree::Tree() { root = NULL; } // Destructor Tree::~Tree() { freeNode(root); } // Free the node void Tree::freeNode(Node* leaf) { if ( leaf != NULL ) { freeNode(leaf->Left()); freeNode(leaf->Right()); delete leaf; } } // Add a node void Tree::addNode(int key) { // No elements. Add the root if ( root == NULL ) { cout Left()); cout Left()); postOrder(n->Right()); cout addNode(10); tree->addNode(20); tree->addNode(40); tree->addNode(50); coutRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.