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