JAVA program to convert an array to binary tree

Posted On // Leave a Comment

CODE:

import java.util.Scanner;

public class arrayToBinaryTree{

    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 cnvrt(int[] ar,int pos){
        if((pos>ar.length-1)||(ar[pos]==-1))
            return null;
        node tmp = new node();
        tmp.data = ar[pos];
        tmp.left = cnvrt(ar,2*pos+1);
        tmp.right = cnvrt(ar,2*pos+2);
        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 = cnvrt(ar,0);
        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: 7
2 1 4 -1 -1 3 5
Inorder traversal of the tree is:
1    2    3    4    5   
Preorder traversal of the tree is:
2    1    4    3    5   
Postorder traversal of the tree is
1    3    5    4    2   

0 comments :

Post a Comment