In order to traverse a tree you could use something like this:

For inorder traversal:

inorder(TreeNode* currentNode)
{
    if (currentNode) {
       inorder(currentNode->LeftChild);
       cout << currentNode->data;
       inorder(currentNode->RightChild);
    }
}

For preorder traversal:

preorder(TreeNode* currentNode)
{
    if (currentNode) {
        cout << currentNode->data;
        preorder(currentNode->LeftChild);
        preorder(currentNode->RightChild);
    }
}

For post order traversal:

postorder(TreeNode* currentNode)
{
    if (currentNode) {
        postorder(currentNode->LeftChild);
        postorder(currentNode->RightChild);
        cout << currentNode->data;
    }
}

For level order traversal:

LevelOrder(TreeNode* root)
{
   Queue q<TreeNode*>;
   TreeNode* currentNode = root;
       
    while (currentNode) {
        cout << currentNode->data;
        if (currentNode->LeftChild) q.Add(currentNode->LeftChild);
        if (currentNode->RightChild) q.Add(currentNode->RightChild);
        currentNode = q.Delete(); //q.Delete returns a node pointer
    }
}

The question is:

How can i make it a bit more graphical......
i mean that with the above methods the output is a list of numbers... is there anyway to modify this code so that i can have a nicer output?

PS: if you give example for one kind of traversal i will find the others by myself :)


Thanks again for your help....

Recommended Answers

All 4 Replies

Member Avatar for iamthwee

I don't think this is easy, the ones that I have seen that look half ok are the ones that plot the tree on its side.

The ones that work the best use a gdi. Drawing that in the console window is always going to be a pain in the ...

I am currently working on a printout for level order for my data structures class. I will post it up here for you.

#
inorder(TreeNode* currentNode)
#
{
#
if (currentNode) {
#
inorder(currentNode->LeftChild);
#
cout << currentNode->data;
#
inorder(currentNode->RightChild);
#
}
#
}

1.
#
2.
inorder(TreeNode* currentNode)
3.
#
4.
{
5.
#
6.
if (currentNode) {
7.
#
8.
inorder(currentNode->LeftChild);
9.
#
10.
cout << currentNode->data;
11.
#
12.
inorder(currentNode->RightChild);
13.
#}
14.
#
15.
}

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.