Hi guys I m going trough the Jumping into C++ book and im currently on the binary tree chapter. There s an exercise that tells me to write a code where I can add values to a binary tree list and then show them in a sorted order (lowest->highest). here s the code I got so far:
Apperently there's something wrong cause every time I run the program and I try to print the values set it only prints le last node I entered instead of the full and sorted list. Any help with that?Code:#include <iostream> using namespace std; struct node { int key; node* p_left = NULL; node* p_right = NULL; }; node* insert (node* p_tree, int key) { if (p_tree == NULL) { node* p_new_node = new node; p_new_node->key = key; p_new_node->p_left = NULL; p_new_node->p_right = NULL; return p_new_node; } if (key < p_tree->key) insert (p_tree->p_left, key); else insert (p_tree->p_right, key); } void print (node* p_tree) { if (p_tree->p_left) { print (p_tree->p_left); } cout<< p_tree->key << '\n'; } void Delete (node* p_tree) { if (!p_tree) return; Delete(p_tree->p_left); Delete(p_tree->p_right); delete p_tree; } int main () { node* p_tree = NULL; int key; int input; cout << "1. Add value" <<endl<<"2. See values in sorted order"<<endl<<"3. Quit"<<endl; cin>> input; while (input != 3) { switch (input) { case 1: cout<< "Enter the value you want to add" << endl; cin >> key; p_tree = insert (p_tree, key);break; case 2: print (p_tree); } cout << "1. Add value" <<endl<<"2. See values in sorted order"<<endl<<"3. Quit"<<endl; cin>>input; } Delete(p_tree); }
p.s. I don' t know what vectors are yet as well as other functions of the Standard Template Library so I must use an approach similar to this one... I guess