Wednesday, February 23, 2011

Java program to build binary tree from preorder traversal and inorder traversal


public TreeNode buildTree(int[] preorder,int[] inorder )
{
 int length_p=preorder.length;
 int length_i=inorder.length;

 if(length_p<1 ||length_i<1 )
    {
 //Wrong input
 return null;
    }

 if(length_p==1)
 { //Stop condition for the recursion;
 TreeNode node=new TreeNode();
 node.left=null;
 node.right=null;
 node.data=preorder[0];
 return node;
 }

 int preorder_root_val=preorder[0];
 int inorder_root_pos=0;

 for(int i=0; i<length_i; i++)
 {// Get the position of the root in inorder array
 if(inorder[i]==preorder_root_val)
 {
 inorder_root_pos=i;
 break;
 }
 }

 //Create arrays which will hold the traversals of
 //left and right subtrees
 int[] newinorder_left=new int[inorder_root_pos];
      int[] newpreorder_left=new int[inorder_root_pos];
 int[] newinorder_right=new int[length_i-inorder_root_pos-1];
      int[] newpreorder_right=new int[length_i-inorder_root_pos-1];

      //Fill the arrays that hold the subtree traversals
 System.arraycopy(inorder, 0, newinorder_left, 0, inorder_root_pos);
 System.arraycopy(preorder, 1, newpreorder_left, 0, inorder_root_pos);
 System.arraycopy(inorder, inorder_root_pos+1, newinorder_right, 0, length_i-inorder_root_pos-1);
 System.arraycopy(preorder, inorder_root_pos+1, newpreorder_right, 0, length_i-inorder_root_pos-1);

 //Create the root Node
 TreeNode treeroot=new TreeNode();
 treeroot.data=preorder[0];

 //Recursive call to buildTree with subtree traversals
 TreeNode leftsubtree=buildTree(newpreorder_left,newinorder_left);
 TreeNode rightsubtree=buildTree(newpreorder_right,newinorder_right);

 //Join the subtrees with the root
 treeroot.left=leftsubtree;
 treeroot.right=rightsubtree;

 //Return the created tree;
 return treeroot;

}

No comments: