Here you will find solutions of many problems on spoj. If you want solution of some problem which is not listed in blog or have doubt regarding any spoj problem (which i have solved) or any programming concept (data structure) you can mail me @ raj.nishant360@gmail.com

And my humble request to you all that don't copy the code only try to understand the logic and algorithm behind the code. I have started this because if you tried as hard as you can and still can't find any solution to the problem then you can refer to this.
You can read my answer how to start competitive programming CLICK HERE

Tuesday, June 17, 2014

IN - ORDER TRAVERSAL IN BINARY SEARCH TREE

Here, is code of  in - order traversal in binary search tree with using recursive method.
All you have to do is follow these steps:

1) Create an empty stack S.
2) Initialize current node as root
   Here starts our loop,
3) Push the current node to S and set current = current->left until current is NULL
4) If current is NULL and stack is not empty then 
     a) Pop the top item from stack.
     b) Print the popped item, set current = current->right 
     c) Go to step 3.
5) If current is NULL and stack is empty then we are done.

#include<stdio.h>
#include<iostream>

using namespace std;

struct node
{
    int val;
    node *left;
    node *right;
}*root;

void make_tree(node **temp,int i)
{
    if((*temp) == NULL)
    {
        (*temp) = new node;
        (*temp)->val = i;
        (*temp)->right = (*temp)->left = NULL;
    }

    else if((*temp)->val > i)
    {
        make_tree(&(*temp)->left,i);
    }

    else
    {
        make_tree(&(*temp)->right,i);
    }
}

void in_order(node *temp)
{
    node *stk[500]; int index = 0;

 stk[index] = temp;
 temp = temp->left;

    while(temp || index != -1)
    {
        if(temp != NULL)
        {
            stk[++index] = temp;
            temp = temp->left;
        }

        else
        {
            temp = stk[index--];
            cout<<temp->val<<"\t";
            temp = temp->right;
        }
    }

    cout<<"\n";
}

int main()
{
    int n,i;

    cin>>n;

    while(n--)
    {
        cin>>i;

        make_tree(&root,i);
    }

    cout<<"In - Order Traversal     :   ";

    in_order(root);

    return 0;
}

No comments:

Post a Comment

Your comment is valuable to us