954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Tree Traversal

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
    }
}


Thequestion 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....

n.aggel
Posting Whiz in Training
203 posts since Nov 2006
Reputation Points: 23
Solved Threads: 12
 

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 ...

iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 

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

Calvin'N'Hobbs
Newbie Poster
1 post since Dec 2008
Reputation Points: 10
Solved Threads: 0
 
#
inorder(TreeNode* currentNode)
#
{
#
if (currentNode) {
#
inorder(currentNode->LeftChild);
#
cout << currentNode->data;
#
inorder(currentNode->RightChild);
#
}
#
}
jbel
Newbie Poster
2 posts since Aug 2010
Reputation Points: 10
Solved Threads: 0
 

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.
}

jbel
Newbie Poster
2 posts since Aug 2010
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You