0
Traverse a Binary Tree
So, I have been trying to figure out the simplest way of doing this, my teacher had asked me to figure it out today, and I don't know if it is because I am hungover or not but after Six Hours I am just confused. can someone help me to figure out, not only how to create a binary tree but how to traverse it?
8 odpowiedzi
+ 2
It can be traversed by three ways.
Inorder,Preorder&Postorder
+ 1
It is created using self-pointers. And it is traversed using recursion.
+ 1
The pre-, in-, and post-order example :
void traverse(Node* node) {
doStuff(node->data); // pre order
traverse(node->left);
doStuff(node->data); // in order
traverse(node->right);
doStuff(node->data); // post order
}
You could also store data from the nodes you visited before so you can access it in the execution of doStuff.
+ 1
You could do that or maybe use a stack?
0
@Desik would it be possible for an example? Like, I think I understand, just need a visual please. I'm a weird leaner, I apologize >.<
0
@Stefan So....maybe make a structure, with a variable to hold some data, and a pointer to two structure for left and right...and three functions for the traversals? but when I create the structures in main, how do I differ the root node from the children?
0
I feel as though this is a common programming moment where I am overcomplicating something, and I am going to face palm once I understand it lol
0
I'll look up Stack, and work on this a little bit. I'll let you guys know how it goes! Thank you both for taking the time to help me out! :D