Saturday, 4 May 2013
Non-Recursive Implementation of Post order traversal in BInary Tree/ BST.
/***************POST ORDER*******************
1. Create a stack and Push NULL as the first element in stack.
2. Initialize a pointer ptr = root to traverse in the tree
3. Initialize a pointer prev = NULL which will store previously processed node.
4. Repeat steps 5 to 6.
5. If ptr is not NULL then
a. push ptr to stack and set ptr = leftChild(ptr).
6. Else
a. Set ptr = Top element of stack
b. If Top element is NULL (ptr = NULL) then return
c. If ptr has right child and RightChild != previously processed node
then set ptr to rightChild(ptr)
d. Else
i. Decrement top of stack.
ii. Process ptr.
iii. Set prev = ptr.
iv. Set ptr = NULL.
COMPLEXITY
Time : O(n)
Space : O(n)
*/
C++ CODE
void iterativePostorder()
{
cout<<"\nPOSTORDER:\n";
int top =0;
node *ptr = root,*prev = NULL;
node* stack[50];
stack[0] = NULL;
while(1)
{
if(ptr != NULL )
{
stack[++top] = ptr;
ptr = ptr->getLeftChild();
}
else
{
ptr = stack[top];
if( ptr == NULL)
return;
if(ptr->getRightChild() != NULL && ptr->getRightChild() != prev )
{
ptr = ptr->getRightChild();
}
else
{
top--;
cout<<" "<<ptr->getData();
prev = ptr;
ptr = NULL;
}
}
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment