Hey guys. I have a project due in 2 weeks, so I have a little bit of time - but I have a lot of work to do, so I want to get this finished. I'm taking a C++ Data Structures class at my high school.. and we have a project that I am stuck on.
It's using Binary Search Trees. I need to input 10 values into the tree, do traversals through the tree (inorder, preorder, and postorder) then indicate which level each node is on. I got the traversals down, however I don't know what how to figure out the level. I'm new to programming in C++, so this may be an easy question that I should be able to figure out. I'm guessing that I should initialize level to -1 (since the level would be base 0), then increment it everytime a node is inserted. The thing is, there can be more than one node on each level, so I'm just completely lost. Can anyone help?
You have the right idea, just at the wrong time. You don't need a counter when inserting into the tree. You need a counter when traversing the tree.
I'm assuming that you are using recursion to implement the walks. That being the case, if you were just to pass a "level number" to the preorder(), postorder(), and inorder() functions and increment and/or decrement it at the right time(s), it might just work...
Thanks - I am still a little confused though. Here is my inorder fuction:
void inorder(node_type *r)
{
if (r != nil)
{
cout << (*r).info <<endl;
inorder((*r).left);
inorder((*r).right);
}
}
I tried incrementing level after and before the 'cout' statement.. but that just made the level go up with each node insertion (so that doesn't work). am I just dumb? i feel like this should be easy