Akhil
Akhil

Reputation: 1

Though i'm performing Inorder Traversal for my Binary Tree, why it's displaying my Right sub Tree first?

I was performing in_order traversal for my binary tree,Instead of displaying my left sub tree first,it's displaying my right sub tree. Please find my bug.

//Inserting

public void Insert(int data)
{
    Node temp=new Node(data);
    
    if(root==null) root=temp;
    else
    {
        Node traverse=root;
        Node parent=root;
        
        while( traverse!=null )
        {
            parent=traverse;
            if(traverse.Data > temp.Data) traverse=traverse.Right;
            else traverse=traverse.Left;
        }
        
        if( parent.Data > temp.Data ) parent.Right=temp;
        else parent.Left=temp;
        
    }
}

//Inorder Traversal

public void display(Node traverse)
{
    if(traverse != null)
    {
        display(traverse.Left);
        System.out.print(traverse.Data+"->");
        display(traverse.Right);
    }
}

My_output

Output should be: 12->15->18->20->22->25->30

Main Function

Node Creation

Upvotes: 0

Views: 26

Answers (1)

trincot
trincot

Reputation: 351029

In insert there is an issue in this code:

            if(traverse.Data > temp.Data) traverse=traverse.Right;
            else traverse=traverse.Left;

As temp holds the data you want to insert, you are here storing lesser values in the right subtree of a node (traverse). It should be the opposite.

The same mistake occurs after the loop, in this code:

    if( parent.Data > temp.Data ) parent.Right=temp;
    else parent.Left=temp;

Upvotes: 0

Related Questions