Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C++ program for a pre-order tree traversal using linked list. Build the

ID: 3680821 • Letter: W

Question

Write a C++ program for a pre-order tree traversal using linked list. Build the tree drawn in the attached photo and then traverse it pre-order, printing each node as it is retrieved.

Build the following tree and then traverse it pre-order, printing each node as it is retrieved. 10

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 preOrder(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); // Add the number of nodes // in the left subtree. count += countNodes(root->right); // Add the number of nodes // in the right subtree. return count; // Return the total. } } // end countNodes() void preorderPrint( TreeNode *root ) { // Print all the items in the tree to which root points. // The item in the root is printed first, followed by the // items in the left subtree and then the items in the // right subtree. if ( root != NULL ) { // (Otherwise, there's nothing to print.) cout right ); // Print items in right subtree. } } // end preorderPrint() int main() Tree* tree = new Tree(); tree->addNode(30); tree->addNode(10); tree->addNode(20); tree->addNode(40); tree->addNode(50); cout
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote