JAVA program to convert a sorted array to BST

Posted On // Leave a Comment

CODE:

import java.util.Scanner;

public class sortedArraytoBST{

    static Scanner in = new Scanner(System.in);

    static void inorder(node tree){
        if(tree==null)
            return;
        inorder(tree.left);
        System.out.print(tree.data+"\t");
        inorder(tree.right);
    }

    static void preorder(node tree){
        if(tree==null)
            return;
        System.out.print(tree.data+"\t");
        preorder(tree.left);
        preorder(tree.right);
    }

    static void postorder(node tree){
        if(tree==null)
            return;
        postorder(tree.left);
        postorder(tree.right);
        System.out.print(tree.data+"\t");
    }

    static node convrt(int[] ar,int start,int end){
        if(start>end)
            return null;
        int mid = (start+end)/2;
        node tmp = new node();
        tmp.data = ar[mid];
        tmp.left = convrt(ar,start,mid-1);
        tmp.right = convrt(ar,mid+1,end);
        return tmp;
    }

    public static void main(String[] args) {
        int len;
        System.out.print("\nEnter length: ");
        len = in.nextInt();
        int[] ar = new int[len];
        int i;
        for(i=0;i<len;i++)
            ar[i] = in.nextInt();
        node tree = new node();
        tree = convrt(ar,0,len-1);
        System.out.println("Inorder traversal of the tree is:");
        inorder(tree);
        System.out.println("\nPreorder traversal of the tree is:");
        preorder(tree);
        System.out.println("\nPostorder traversal of the tree is");
        postorder(tree);
    }
}

OUTPUT:

Enter length: 5
1 2 3 4 5
Inorder traversal of the tree is:
1    2    3    4    5   
Preorder traversal of the tree is:
3    1    2    4    5   
Postorder traversal of the tree is
2    1    5    4    3   

0 comments :

Post a Comment