/*******************INORDER*****************
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. Repeat steps 4 to 5.
4. If ptr is not NULL then
a. push ptr to stack and set ptr = leftChild(ptr).
5. Else
a. Pop top element from stack and assign it to ptr.
b. If NULL is popped then return
c. Process Node
d. If ptr has right child then set ptr to rightChild(ptr)
e. Else set ptr = NULL.
COMPLEXITY
Time : O(n)
Space : O(n)
*/
void iterativeInorder()
{
cout<<"\nINORDER:\n";
int top =0;
node *ptr = root;
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;
cout<<" "<<ptr->getData();
if(ptr->getRightChild() != NULL)
ptr = ptr->getRightChild();
else
ptr = NULL;
}
}
}
No comments:
Post a Comment