Skip to main content

Construct Binary Tree using PostOrder And Inorder in Java




We have “post order” and “in order” of binary search tree. We have to construct the Binary Tree with this information.


First we should know that there is unique Binary Tree with one PostOrder and InOrder.
So below I am explaining how to construct the Binary Tree:
PostOrder Traversal: {D, E, B, F, C, A}
InOrder Traversal: {D, B, E, A, F, C}
  1. If we have PostOrder then last element will be root. If PostOrder traversal is :           {D, E, B, F, C, A} then ‘A’ will be root.
  2. We will search ‘A’ in InOrder traversal we got it @ index 3.
  3. Whatever present from 0-2 will be present in left sub tree of Root Node ‘A’ and from index 4-5 will be present in right sub tree of A as follows.
  4. Screenshot from 2016-09-03 23:51:41.png
    After first step
  5. And now we will check for second last element from postOrder that is ‘C’
  6. We will check ‘C’ in InOrder array, and ‘C’ is present at last location that means ‘F’ will be its left child as follows:
  7. Order of nodes whether they will be in left or right, can be determined from inOrder array. 
  8. Screenshot from 2016-09-03 23:50:06.png
    After second step
  9. Again traverse post order array from right and after A and C we will get ‘F’ and search it in InOrder but there is no need as F is leaf node.
  10. Next from post order list comes ‘B’, check ‘B’ in InOrder array.
  11. We got ‘B’ in InOrder array at position ‘1’, now as we can see that at left of ‘B’ (in InOrder) there is ‘D’ so D will be its left child and in right of ‘B’ there is ‘E’ so ‘E’ will be its right child.
  12. Screenshot from 2016-09-03 23:58:45.png
    Final Binary Tree
Similar approach can be applied over Binary Search Tree also.
Java Code
//Java program to construct a tree using inorder and postorder traversal

/* A binary tree node has data, reference to left child
and a reference to right child */
class Node 
{
 char data;
 Node left, right;

 Node(char item) 
 {
     data = item;
     left = right = null;
 }
}

public class BinaryTreeUsingPreorderAndInorder 
{
     Node root;  // Declaring root reference
     static int postIndex = 0; // keeps track of index in postOrder array
     
     // Constructor to initialize size of postIndex to array length - 1
     public BinaryTreeUsingPreorderAndInorder(int len){postIndex=len-1;}

     /* Recursive function to construct binary tree of size len from
        Inorder traversal in[] and PostOrder traversal pre[].
        Initial values of inStrt and inEnd should be 0 and len -1.  
        inStrt and inEnd are indices of InOrder array.
        */
    
    // return type of this function is of type Node
    Node buildTree(char[] in, char[] post, int inStrt, int inEnd){
 
        // Condition to break recursion
        if(inStrt > inEnd)
      return null;

        /* Pick current node from PostOrder traversal using postIndex
        and decrement postIndex */
        
        // Create a new Node
        Node tNode = new Node(post[postIndex--]);
        
        /* If this node has no children then return */
        if(inStrt == inEnd)
                return tNode;
        
        // Search the elements from postOrder in inOrder array
        // search will return index of element
        int inIndex = search(in,inStrt, inEnd, tNode.data);
        
        /* Using index from Inorder traversal, construct right and
        left subtrees  again using recurstion
        */
        // First create right sub tree from inIndex+1 to inEnd 
        tNode.right = buildTree(in, post, inIndex+1, inEnd);
        // And then create left sub tree from inStrt to inIndex-1 
        tNode.left = buildTree(in, post, inStrt, inIndex-1);

        // At last return the root of the tree        
        return tNode;
    }
    
     /* Function to find index of value in arr[start...end]
      The function assumes that value is present in in[] */
     int search(char arr[], int strt, int end, char value) 
     {
         int i;
         for (i = strt; i <= end; i++) 
         {
             if (arr[i] == value)
                 return i;
         }
         return i;
     }

     /* This funtcion is here just to test buildTree() */
     void printInorder(Node node) 
     {
         if (node == null)
             return;
    
         /* first recur on left child */
         printInorder(node.left);
    
         /* then print the data of node */
         System.out.print(node.data + " ");
    
         /* now recur on right child */
         printInorder(node.right);
     }
     
     // driver program to test above functions
     public static void main(String args[]) 
     {
         char in[] = new char[]{'D', 'B', 'E', 'A', 'F', 'C'};
         char post[] = new char[]{'D', 'E', 'B', 'F', 'C', 'A'};

         BinaryTreeUsingPreorderAndInorder tree = 
         new BinaryTreeUsingPreorderAndInorder(post.length); 
         int len = in.length;
         /* calling buildTree method to create 
          * tree using postOrder and InOrder 
         */ The function returns reference to the root node.
         Node root = tree.buildTree(in, post, 0, len - 1);
         // inorder traversal of build tree
         System.out.println("Inorder traversal of constructed tree is : ");
         tree.printInorder(root);
     }
}

Comments

Popular posts from this blog

Goodness of Fit Test for normal and poisson distribution

Meaning of Goodness of fit test: We find out which distribution fits the sample data the most. And this is achieved using chi-square distribution (Snedecor and Cochran, 1989). How to apply: There are 4 steps to follow: State the hypothesis:  Data follows a distribution or not Criteria to reject null hypothesis: if Χ 2  > Χ 2 (k,1-α) then reject null hypothesis. Analyze sample data: Compute the chi-square value using below formula: ∑(Oi- Ei) 2 /Ei        : Oi is observed frequency and Ei is expected frequency Interpret the results: Declare the results after comparing the values of Χ 2 and Χ 2 (k,1-α), where k is degree of freedom and  α is significance level. Degree of Freedom: It is  =  n - 1 - m m: number of parameter in the distribution. So in case of normal distribution m is 2 ( μ ,α) and in case of poisson dist. m is = 1 ( λ). Example 1: Goodness of fit test for Normal Distribution Year wise data is given about number of car accidents, find out w

classification of database indexing

Dense Index: For every records we are having one entry in the index file. Sparse Index: Only one record for each block we will have it in the index file. Primary Index ( Primary Key + Ordered Data )  A primary index is an ordered file whose records are fixed length size with 2 fields. First field is same as primary key and the second field is pointer to the data block.  Here index entry is created for first record of each block, called ‘block anchor’. Number of index entries thus are equal to number of blocks Average number of block accesses are = logB (worst case) + 1 (best case),  So on average it will be O(logB) The type of index is called sparse index because index is not created for all the records, only the first records of every block the entry is made into the index file. Example on Primary Index Number of Records = 30000, Block Size = 1024 Bytes, Strategy = Unspanned, Record Size = 100 Bytes, Key Size = 6 Bytes, Pointer Size = 9 Bytes, Then find avera

Red Black Tree Insertion in Java

Red Black Tree is a binary search tree. With extra property with each node having color either RED or BLACK. It has following properties: Every node is either RED or BLACK Root element will have BLACK color. Every RED node has BLACK children. Every path from root to leaf will have same number of BLACK nodes. We have few theorems over RB tree: Note: Height of RB tree is θ(logn). Insertion: Insertion in RB tree is little tricky as compared to BST, we have following cases to insert a node in RB tree: When tree is null just insert the node and it will be root, color will be BLACK. To insert an element first find its position: if key <= node.key then move to left else move to right Once we find the correct place to insert, we insert the node with color RED. But if the parent of the node just inserted has color RED then it will violate 3 property. So we have to fix this issue. We call it double RED problem, we resolve it using following few cases. DOUBLE R