I want to add values to a binary search tree taking input from user until -1 is encountered. It must then continue to read numbers and delete from the tree until I encounter a -1 again. After taking both inputs it should print the pre-order, in-order and post-order traversals after each number was removed.
My code below is printing the traversals in between the taking of input of the values which will be removed and not at the end
Input:
//These values will be added to tree
50
30
35
61
24
58
62
32
-1
//These values will be removed from tree
30
24
32
-1
Expected Output:
50 32 24 35 61 58 62
24 32 35 50 58 61 62
24 35 32 58 62 61 50
50 32 35 61 58 62
32 35 50 58 61 62
35 32 58 62 61 50
50 35 61 58 62
35 50 58 61 62
35 58 62 61 50
My input and output
50
30
35
61
24
58
62
32
-1
30
50 32 24 35 61 58 62
24 32 35 50 58 61 62
24 35 32 58 62 61 50
24
50 32 35 61 58 62
32 35 50 58 61 62
35 32 58 62 61 50
32
50 35 61 58 62
35 50 58 61 62
35 58 62 61 50
-1
int main()
{
Node *root = NULL;
int num;
cin >> num;
while (num != -1)
{
root = insert(root, num);
cin >> num;
}
cin >> num;
while (num != -1)
{
root = deleteNode(root, num); // delete from tree
preorder(root); // print preorder
cout << endl;
inorder(root); // print inorder
cout << endl;
postorder(root); //print postorder
cout << endl;
cin >> num;
}
return 0;
}
CodePudding user response:
Yes, your code writes the traversals after it reads each number to be deleted. I gather you want the writing to be done after all the reading is done.
As commenters say, there's two ways. Either you can buffer the input, or you can buffer the output. The input buffer is a bit simpler, so I'll demonstrate that way. The first thing to note is that you don't know how big the buffer will need to be until you get to the -1. So you could either allocate a "big enough" buffer and hope for the best, or use an expanding buffer. In C , expanding buffers are easy - they're called vector
's.
//Get access to C 's standard vector library
#include <vector>
int main()
{
Node *root = NULL;
int num;
cin >> num;
while (num != -1)
{
root = insert(root, num);
cin >> num;
}
//create the inputBuffer, initially empty.
std::vector<int> inputBuffer;
cin >> num;
while (num != -1)
{
//Instead of producing the output straight away, just buffer the input num.
inputBuffer.push_back(num);
cin >> num;
}
//Now we've buffered all the input, get going on producing the output.
for(int i=0; i<inputBuffer.size(); i )
{
int num = inputBuffer[i];
root = deleteNode(root, num); // delete from tree
preorder(root); // print preorder
cout << endl;
inorder(root); // print inorder
cout << endl;
postorder(root); //print postorder
cout << endl;
}
return 0;
}