Traversing a Binary Tree!

Nov 3, 2011 at 5:21pm
hey fellas. i am working on an assignment that wants me to traverse through a binary tree using inOrder, postOrder, preOrder, and levelOrder traversing. Here is the code we have been provided so far: http://pastebin.com/kWHCBavL

Our instructor has written the code to insert the values in the the tree, we just have to create the functions to traverse and print the values, and it will compare them to the real order. This is the code I have so far for the traversals:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
void inOrder(BSTNode* root)
{
        if(root)
        {
                inOrder(root->left);
                cout << root->value + " " <<;
                inOrder(root->right);
        }
}

void postOrder(BSTNode* root)
{
        if(root)
        {
                postOrder(root->left);
                postOrder(root->right);
                cout << root->value + " " <<;
        }
}

void preOrder(BSTNode* root)
{
 
 
}
 
 
void levelOrder(BSTNode* root)
{
 
 
}


My question is, does this seem correct? With what I know about traversing, the inOrder and postOrder seem correct. Our instructor wants us to implement preOrder using a stack: "Do not use recursion! While this function could be implemented recursively, use a while loop along with a stack." I'm not sure how to implement preOrder with a stack && while loop..

Thanks guys,any input will be appreciated.
Nov 3, 2011 at 5:45pm
After searching and looking at some examples, I came up with this for the stack implementation of the preOrder traversing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
void preOrder(BSTNode* root)
{
        //create a stack to store the node values and
        //create a temporary pointer to the nodes
        stack preO;
        BSTNode *temp;

        //push the root node onto the stack
        preO.push(root);

        while(!root.empty())
        {
                //root is popped out and printed during
                //the first iteration of the loop
                temp = preO.pop();
                cout << temp->value + " " <<;

                //if temp has a right or left child, push
                //that child onto the stack
                if(temp->right)
                        preO.push(temp->right);
                if(temp->left)
                        preO.push(temp->left)
        }
}


Right now I'm still trying to figure out how to implement the levelOrder traversing. Our instructor wants us to use a queue for the levelOrder traversing.
Last edited on Nov 3, 2011 at 5:45pm
Topic archived. No new replies allowed.