Tuesday, November 25, 2008

Binary Tree -Depth First Traversal - Recursive / Non Recursive

#include "stdafx.h"
#include < iostream >
#include < stack >
using namespace std;
struct Node{
Node* Left;
Node* Right;
int Val;
};
void InsertNode(Node** ppNode,int val)
{
if(ppNode == NULL)
return;
if(*ppNode == NULL)
{
*ppNode = new Node();
(*ppNode)->Val = val;
(*ppNode)->Left = (*ppNode)->Right = NULL;
}
else
{
if(val > (*ppNode)->Val)
InsertNode(&((*ppNode)->Right),val);
else
InsertNode(&((*ppNode)->Left),val);
}
}
void PreOrderRecursive(Node* pNode)
{
cout<<" "<Val;
if(pNode->Left)
PreOrderRecursive(pNode->Left);
if(pNode->Right)
PreOrderRecursive(pNode->Right);
}
void PreOrderNonRecursive(Node* pNode)
{
bool done;
stacks;
Node * cursor = pNode;
done = false;

while(!done)
{
if(cursor != NULL)
{
cout<<" "<Val;
s.push(cursor);
cursor = cursor->Left;
}
else
{
if(!s.empty())
{
cursor = s.top();
s.pop();
cursor = cursor->Right;
}
else
{
done = true;
}
}
}
}
void InOrderRecursive(Node* pNode)
{
if(pNode->Left != NULL)
InOrderRecursive(pNode->Left);
cout<<" "<Val;
if(pNode->Right != NULL)
InOrderRecursive(pNode->Right);
}

void InOrderNonRecursive(Node* pNode)
{
bool done;
stack s;

Node* cursor = pNode; //set cursor to root of binary tree
done = false;

while (!done)
{
if(cursor != NULL)
{
s.push(cursor); //place pointer to node on the stack
//before traversing the node's left subtree
cursor = cursor->Left; //traverse the left subtree
}
else //backtrack from the empty subtree and
//visit the node at the top of the stack;
//however, if the stack is empty, you are
//done
{
if (!s.empty())
{
cursor = s.top();
s.pop();
cout <<" "<Val;
cursor = cursor->Right;
}
else
done = true;
}
}


}
void PostOrderRecursive(Node* pNode)
{
if(pNode->Left != NULL)
PostOrderRecursive(pNode->Left);
if(pNode->Right != NULL)
PostOrderRecursive(pNode->Right);
cout<<" "<Val;
}

int _tmain(int argc, _TCHAR* argv[])
{
Node* Head = NULL;
InsertNode(&Head,6);
InsertNode(&Head,4);
InsertNode(&Head,5);
InsertNode(&Head,2);
InsertNode(&Head,3);
InsertNode(&Head,1);
InsertNode(&Head,8);
InsertNode(&Head,7);
InsertNode(&Head,9);
cout< < "Recursive Inorder Traversal :";
InOrderRecursive(Head);
cout< < endl < < "Non recursive Inorder Traversal :";
InOrderNonRecursive(Head);
cout< < endl < <"Recursive Preorder Traversal :";
PreOrderRecursive(Head);
cout< < endl < < "Non recursive Preorder Traversal :";
PreOrderNonRecursive(Head);
cout< < endl < < "Recursive Postorder Traversal :";
PostOrderRecursive(Head);
return 0;
}

No comments: