Thursday, March 26, 2015

Serialize and De-serialize a Binary Tree

Ref :- "Serialize and De-serialize a Binary Tree" (http://www.geeksforgeeks.org/serialize-deserialize-binary-tree/

Given solution :- The solution given for "How to store a general Binary Tree?" is to store BOTH Inorder and Preorder traversals.
This approach is 
1) time consumming :- as you have to do two traversal
2) Space consuming :- as this solution requires space twice the size of Binary Tree. (As mentioned in article)


My approach :- I have better approach which requires only 1 traversal and memory only equal to tree
A tree can be specified as an array of Tree node objects. And another array that will represent the parent child relation.
e.g.

 
Thus we need to store all nodes in in-order traversal and an additional string that gives mapping. e.g. in above case 1,4,3,1,-1,6,4,6,7

We can build this string while we are doing in-order traversal. Thus NO second traversal

De-Serialization is also very easy. We just need to de-serialize nodes in same sequence. And then based on the mapping string just adjust the pointers. 


Java Code :- Only serialization part


package treerelated;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class TreeNode {
public int value;
public TreeNode left,right;
public TreeNode(int value) {
super();
this.value = value;
}
public int findFullNodes(){
int total = 0;
if(left!=null)
total += left.findFullNodes();
if(right !=null) 
total += left.findFullNodes();
if(left!=null && right !=null)
total +=1;
return total;
}
@Override
public String toString() {
return ""+value;
}
public static ArrayList<TreeNode> nodeList; 
public static Map<Integer,Integer> parentChildRelationMap;
public static int currCount ;
public static void inOrderTraversal(TreeNode root){
nodeList = new ArrayList<TreeNode>();
parentChildRelationMap = new HashMap<Integer, Integer>();
currCount = -1;
inOrderTraversal_internal(root);
System.out.println("Printing Array");
for(int i=0;i<nodeList.size();i++){
System.out.print(nodeList.get(i)+" ");
}
System.out.println("\nparentChildRelationMap=");
for(Integer i :parentChildRelationMap.keySet()){
System.out.println(i +" has parent "+parentChildRelationMap.get(i));
}
}
public static int inOrderTraversal_internal(TreeNode root){
if(root==null) return currCount;
else {
int countBefore = currCount;
int returnedCount = inOrderTraversal_internal(root.left);
System.out.println(root.value);
nodeList.add(root);
currCount++;      
if(countBefore!=returnedCount){
// It means some child nodes were added
// Child node was added on  returnedCount and parent is added on currCount
parentChildRelationMap.put(returnedCount,currCount);
}
countBefore = currCount; // So countBefore-1 represents the position of parent node of rightside tree
returnedCount= inOrderTraversal_internal(root.right);
if(countBefore!=returnedCount){
// It means some child nodes were added
// Child node was added on  returnedCount and parent is added on countBefore-1
parentChildRelationMap.put(returnedCount,countBefore);
}
// return countBefore-1 to indicate where this node was added
return countBefore;
}
}

}


package treerelated;

public class TreeOperations {


public static void main(String[] args) {
TreeNode t1 = new TreeNode(10);
t1.left = new TreeNode(20);
t1.right = new TreeNode(30);

t1.left.left = new TreeNode(40);
t1.left.right = new TreeNode(50);
t1.right.left = new TreeNode(60);
t1.right.right = new TreeNode(70);
t1.left.right.left = new TreeNode(80);
t1.right.right.right = new TreeNode(90);
TreeNode.inOrderTraversal(t1);
}

}

Output :-

40
20
80
50
10
60
30
70
90
Printing Array
40 20 80 50 10 60 30 70 90 
parentChildRelationMap=
0 has parent 1
1 has parent 4
2 has parent 3
3 has parent 1
5 has parent 6
6 has parent 4
7 has parent 6
8 has parent 7

Saturday, February 28, 2015

Count number of islands where every island is row-wise and column-wise separated

Reference :- 
http://www.geeksforgeeks.org/count-number-islands-every-island-separated-line/

Problem statement :- 
Given a rectangular matrix which has only two possible values ‘X’ and ‘O’. The values ‘X’ always appear in form of rectangular islands and these islands are always row-wise and column-wise separated by at least one line of ‘O’s. Note that islands can only be diagonally adjacent. Count the number of islands in the given matrix.

Examples:
mat[M][N] =  {{'O', 'O', 'O'},
              {'X', 'X', 'O'},
              {'X', 'X', 'O'},
              {'O', 'O', 'X'},
              {'O', 'O', 'X'},
              {'X', 'X', 'O'}
             };
Output: Number of islands is 3

mat[M][N] =  {{'X', 'O', 'O', 'O', 'O', 'O'},
              {'X', 'O', 'X', 'X', 'X', 'X'},
              {'O', 'O', 'O', 'O', 'O', 'O'},
              {'X', 'X', 'X', 'O', 'X', 'X'},
              {'X', 'X', 'X', 'O', 'X', 'X'},
              {'O', 'O', 'O', 'O', 'X', 'X'},
             };
Output: Number of islands is 4


My approach :-
The article mentions straightforward option to find-out the number of rectangles. This has complexity of O(mn).
If we are allowed to use a little more memory we can take different approach.
Here we traverse row by row. As soon as we come across a "X" we find out all the boundaries of that island and save it in a list. 
When in next row we come across other "X" we can check if it falls under already considered island. In that case we do not need to check columns which fall in that rectangle. We can directly jump to column outside islands. 
This way we can skip some iterations. Also at the end we get list of all rectangle. Which is an added advantage.
Java implementation 
Also shared at http://ideone.com/IlpH9t 
package matrix;
import java.util.ArrayList;
public class RectangularIslands {
public static void main(String[] args) {
char[][] mat1   =  
    {{'O', 'O', 'O'},
             {'X', 'X', 'O'},
             {'X', 'X', 'O'},
             {'O', 'O', 'X'},
             {'O', 'O', 'X'},
             {'X', 'X', 'O'}
            };
findIslands(mat1);
char[][] mat2 =  
    {{'X', 'O', 'O', 'O', 'O', 'O'},
             {'X', 'O', 'X', 'X', 'X', 'X'},
             {'O', 'O', 'O', 'O', 'O', 'O'},
             {'X', 'X', 'X', 'O', 'X', 'X'},
             {'X', 'X', 'X', 'O', 'X', 'X'},
             {'O', 'O', 'O', 'O', 'X', 'X'},
            };
findIslands(mat2);
char[][] mat3 =
 {{'X', 'O', 'O', 'O', 'O', 'O'},
             {'O', 'O', 'X', 'O', 'X', 'X'},
             {'O', 'O', 'O', 'O', 'O', 'O'},
             {'X', 'O', 'X', 'O', 'X', 'X'},
             {'X', 'O', 'X', 'O', 'X', 'X'},
             {'O', 'O', 'O', 'O', 'X', 'X'},
            };
findIslands(mat3);
char[][] mat4 =
 {{'X', 'X', 'X', 'X', 'X', 'X'},
{'X', 'X', 'X', 'X', 'X', 'X'},
{'X', 'X', 'X', 'X', 'X', 'X'},
{'X', 'X', 'X', 'X', 'X', 'X'},
{'X', 'X', 'X', 'X', 'X', 'X'},
{'X', 'X', 'X', 'X', 'X', 'X'},
           };
findIslands(mat4);
}
public static ArrayList<RectangularIslands.Island> islandList;
public static void findIslands(char[][] matrix) {
islandList = new ArrayList<RectangularIslands.Island>();
int i=0,j=0;
int matrixRows = matrix.length;
int matrixCols = matrix[0].length;
while(i<matrixRows){
j=0;
while(j<matrixCols){
if(matrix[i][j] =='X'){
// Check if this position is already considered in previously observed island
Island notedIsland =  isInIsland(i,j);
if(notedIsland!=null){
// point is already in noted island. So directly jump to position outside island
j=notedIsland.endPointColnum+1;
}else{
int startPointRownum = i;
int startPointColnum = j;
j++;
// We have found top-left corner of island. Now find the boundaries
while(j<matrixCols && matrix[i][j]=='X'){
j++; // Keep moving right till we find X or end of matrix
}
int endPointColnum = j-1; // Current j points to 'O' or matrix boundry
// Find the bottom of island 
int k=i;
while(k+1<matrixRows && matrix[k+1][startPointColnum]=='X'){
// Keep moving right till we find X or end of matrix
k++;
}
int endPointRownum = k;
// Create rectangle object and add to list
Island ilnd = new Island();
ilnd.startPointRownum=startPointRownum;
ilnd.startPointColnum=startPointColnum;
ilnd.endPointRownum=endPointRownum;
ilnd.endPointColnum=endPointColnum;
islandList.add(ilnd);
}
}else{
j++;
}
}
i++;
}
System.out.println("No of islands ="+islandList.size());
}
static private class Island{
public int startPointRownum,startPointColnum,endPointRownum,endPointColnum;
}
public static Island isInIsland(int rownum, int colnum){
for(Island ilnd:islandList){
if(ilnd.startPointRownum<=rownum && ilnd.startPointColnum<=colnum && ilnd.endPointRownum>=rownum && ilnd.endPointColnum>=colnum){
return ilnd;
}
}
return null;
}
}
Output :- 
No of islands =3
No of islands =4
No of islands =6
No of islands =1

Saturday, November 15, 2014

Given a number, find the next smallest palindrome

Reference
http://www.geeksforgeeks.org/given-a-number-find-next-smallest-palindrome-larger-than-this-number/

Problem statement
Given a number, find the next smallest palindrome larger than this number. 
For example, 
if the input number is “2 3 5 4 5″, the output should be “2 3 6 3 2″. 
if the input number is “9 9 9″, the output should be “1 0 0 1″.
if the input number is “1 9 1″, the output should be “2 0 2″.

My approach.


Please find below recursive approach for find the next smallest palindrome"

Algorithm :- 
If number is all 9's say 99 then then its palindrome will be 101. For 999 answer is 1001 and so on

For other cases 
if input is 1356 then we will start with first & digit same as input 1 _ _ 1
Now we will call same function to get palindrome of internal number by striping first and last digit viz. 35. 
So function call for 35 will return 44
So answer for 1356 is 1 4 4 1

Now if number is 1996 the we will start with 1 _ _ 1
Now we will call same function to get palindrome of internal number by striping first and last digit viz. 99. 
So function call for 99 will return 101
So it returned palindrome of length more than 2; it means we should increase outer digit to make it 2 _ _ 2
And we should fill it up with zeros.
Thus answer for 1996 is 2002

Code is shared at 
http://ideone.com/3sGpMr

Java code
package stringsequennce;

import java.util.ArrayList;
import java.util.List;

public class NextBiggerPalindromeNumber {

/**
Given a number, find the next smallest palindrome
Given a number, find the next smallest palindrome larger than this number. For example, if the input number is “2 3 5 4 5″, the output should be “2 3 6 3 2″. And if the input number is “9 9 9″, the output should be “1 0 0 1″.

The input is assumed to be an array. Every entry in array represents a digit in input number. Let the array be ‘num[]’ and size of array be ‘n’

There can be three different types of inputs that need to be handled separately.
1) The input number is palindrome and has all 9s. For example “9 9 9″. Output should be “1 0 0 1″
2) The input number is not palindrome. For example “1 2 3 4″. Output should be “1 3 3 1″
3) The input number is palindrome and doesn’t have all 9s. For example “1 2 2 1″. Output should be “1 3 3 1″.
*/
public static void main(String[] args) {
// for(int i=1;i<10;i++){
// System.out.println("i= "+i+" "+getMaxPalindromeOfLenthN(i));
// }
int num=0;

num=999 ;
System.out.println("num= "+num +" palindrome ="+ getNextHigherPalnidromeNumber(num));

num=1234;
System.out.println("num= "+num +" palindrome ="+ getNextHigherPalnidromeNumber(num));

num=191;
System.out.println("num= "+num +" palindrome ="+ getNextHigherPalnidromeNumber(num));

}
public static int getNextHigherPalnidromeNumber(int input){
// Handle single digit numbers
if(input==9) return 11;     // For 9 next palindrome is 11

if(input<9) return input+1; // for 0 to 8 next palindrome is next number

// So now number is two digits or more
// Separate out digits 
int temp = input;
ArrayList<Integer> digitList = new ArrayList<Integer>();
while(temp>0){
digitList.add(temp%10);
temp = temp /10;
}
// digitList(0) is digit at unit place
// digitList(n) will be digit at highest place.

// Now check if input is equal to max palindrome of that length
// In that case next palindrome is min palindrome of lenght+1
if(input==getMaxPalindromeOfLenthN(digitList.size())) 
return getMinPalindromeOfLenthN(digitList.size()+1);

// It is not max palindrome of that length. next palindrome is of same length as input.
/* if input is 1356 then we will start with first & digit same as input 1 _ _ 1
*  Now we will call same function to get palindrome of internal number by striping first and last digit viz. 35. So function will return 44
*  So answer is 1 4 4 1
*  
*  Now if number is 1996 the we will start with 1 _ _ 1
*  Now we will call same function to get palindrome of internal number by striping first and last digit viz. 99. So function will return 101
*  So it returned palindrome of length more than 2; it means we should increase outer digit
*  2 _ _ 2
*  And we should fill it up with zeros so answer for 1996 is 2002
*  
*/

// Strip first and last digit
//  for number 7986  List is -> 6,8,9,7
// So starting with digit at index n-2 till index 1; prepare number
int outerdigit   =digitList.get(digitList.size()-1);
// So 7 _ _ 7   is time being 7007.
int returnVal = outerdigit*(int)Math.pow(10,digitList.size()-1) + outerdigit;

temp = 0;
for(int i=digitList.size()-2;i>=1;i--){
temp = temp*10 + digitList.get(i);
}
int palindromeForInnerNumber= getNextHigherPalnidromeNumber(temp);

// for inner number 99 palindrome will be 101. In this case we should increase higher number and use all zeros
// Inner number is of length digitList.size()-2. So palindrome of biggger length id digitList.size()-2+1
// For input number 79998 inner number is 999. And its palindrome is 1001. 
// Now outer number was decided as 7 and we had prepared temporary palindrome as 7_ _7. So we should make it 8_ _ 8 means 8008
if(palindromeForInnerNumber==getMinPalindromeOfLenthN(digitList.size()-2+1)){  
outerdigit++;
returnVal = outerdigit*(int)Math.pow(10,digitList.size()-1)+ outerdigit;
}else{
//  For input 7865 palindrome is decided as 7_ _7 i.e. 7007. Inner number is 86. Its palindrome is 99.
// Now 99 is to be fit into middle slot. So we will multiply it by 10 and add into number
// 7007 + 99*10 = 7007 + 990= 7997
returnVal= returnVal+ palindromeForInnerNumber*10 ;
}
return returnVal;
}

public static int getMinPalindromeOfLenthN(int n){
/* For length min palindromes are as follows
* 1 1
*   2 11
*   3 101
*   4 1001
*   5 10001
*/
// So 1 is present at  10^(n-1) and unit digit
// so number is 10^(n-1) + 1
if(n==1) 
return 1;

return (int)Math.pow(10, n-1) + 1;
}

public static int getMaxPalindromeOfLenthN(int n){
/* For legth max palindromes are as follows
* 1 9
*   2 99
*   3 999
*   4 9999
*/
int num =0;
for(int i=1;i<=n;i++){
num = num*10+9;
}
return num;
}


}



Sunday, November 2, 2014

Lowest Common Ancestor (LCA) in a Binary Tree

Reference :- 
http://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/

My approach :-
Method using single traversal & flags(v1 and v2) given in article can be improved further.
There we call find(lca, n2) & find(lca, n1). 
So you are traversing tree twice for looking up two keys.
What if n1 is somewhere down n2 ? All the traversal to reach till n1 is done again. 
Instead you should traverse tree just once and keep track of values found. If you find one key still continue searching further for other key. So all the traversal till this point is not needed again. 
Once you find both keys stop search.

So you maintain two flags to indicate of values are found. Initially both flags are false.
If root is equal to one value then corresponding flag is set.
Then we search sub-trees to in same way. 
After traversal is complete; if if both flag were false before this node checking and both flag are true after this node checking then this node it LCA


Java implementation 
Code is also shared at
http://ideone.com/McU0wN

package tree;

public class TreeNode {
int numKey;
char charKey;
public TreeNode left, right;


TreeNode(int keyVal){
numKey=keyVal;
}

TreeNode(char keyVal){
charKey=keyVal;
}

TreeNode(char keyVal,TreeNode leftChild, TreeNode rightChild){
charKey=keyVal;
left=leftChild;
right=rightChild;
}

public static TreeNode findLCA(TreeNode root, int val1, int val2){
LCA lcaObj = new LCA();
lcaObj.val1=val1;
lcaObj.val2=val2;
return findLCA_internal(root,lcaObj);

}

private static TreeNode findLCA_internal(TreeNode root,LCA lcaObj ){
if(root==null) return null;

if(lcaObj.val1Found && lcaObj.val2Found){
// both values are found at previous level so do nothing more
return null;
}else{
boolean val1FlagBefore = lcaObj.val1Found;
boolean val2FlagBefore = lcaObj.val2Found;

if(!lcaObj.val1Found && root.numKey==lcaObj.val1){
lcaObj.val1Found=true;
}if(!lcaObj.val2Found && root.numKey==lcaObj.val2){
lcaObj.val2Found=true;
}
TreeNode lcaPresentInLeftTree = findLCA_internal(root.left,lcaObj);
if(lcaPresentInLeftTree !=null){
return lcaPresentInLeftTree;
}else{
TreeNode lcaPresentInRightTree  = findLCA_internal(root.right,lcaObj);
if(lcaPresentInRightTree!=null) {
return lcaPresentInRightTree;
}else{
// LCA is not presnt in left tree nor it is present in right tree. So check if this node itself if LCA
//  before this node was checked ;val1 flag was false and afterwards it is true.
// ALSO
// before this node was checked; val2 flag was false and and afterwards it is true.
// This root is the LCA
if(!val1FlagBefore && lcaObj.val1Found && !val2FlagBefore && lcaObj.val2Found){
return root;
}else{
// So either or both of keys are not present in this tree
return null;
}

}
}

}
}

public static void main(String[] args) {
/*
10
/ \
   20  30
   / \
  40 50
  */
TreeNode root = new TreeNode(10);
root.left= new TreeNode(20);
root.left.left= new TreeNode(40);
root.left.right= new TreeNode(50);
root.right= new TreeNode(30);

TreeNode lcaNode = null;
lcaNode = findLCA(root, 50, 40);
System.out.println("findLCA(root, 50, 40)" + lcaNode.numKey );
lcaNode = findLCA(root, 30, 40);
System.out.println("findLCA(root, 30, 40)"+ lcaNode.numKey );
lcaNode = findLCA(root, 30, 20);
System.out.println("findLCA(root, 30, 20)"+ lcaNode.numKey );
lcaNode = findLCA(root, 50, 20);
System.out.println("findLCA(root, 50, 20)"+ lcaNode.numKey );

}

}


class LCA{
int val1,val2;
boolean val1Found=false;
boolean val2Found=false;

}


Output
findLCA(root, 50, 40)20
findLCA(root, 30, 40)10
findLCA(root, 30, 20)10
findLCA(root, 50, 20)20

Sunday, October 19, 2014

Find the height of the tree represented as array

Reference :-
http://www.geeksforgeeks.org/amazon-interview-experience-set-134-campus-sde
"Attempt 2 F2F – Round 3: Q3"

Problem statement :-
An array is given whose every ith index is the child node of a[i] as shown in the example below. The root node is represented by -1. 
Find the height of the tree.I did it in linear time.

Input: parent[] = {1 2 -1 2}
index                     0 1 2  3

for index 2 value is -1. So it is root   2
for index and index 3 value is 2. So they are child of 2  
          2
        /  \
       1    3
     
for index 0 value is 1. So it is child of 1

         2
        /  \
       1    3
      /    
     0

Height of this tree is 3

My approach :- 
Height of the tree  = maximum number in the array + 1 =  2+1 =3


Another example
Input: parent[] = 1 3 -1  2  1
Index                  0 1  2  3  4

Tree is 
     2
    /
   3
  /
 1
/ \
0  4
    \
     5

Height of this tree is 5

My approach :- 
Height of the tree  = maximum number in the array + 1 =  4+1 =5

Saturday, October 18, 2014

Construct Full Binary Tree from given preorder and postorder traversals

Reference
http://www.geeksforgeeks.org/full-and-complete-binary-tree-from-given-preorder-and-postorder-traversals/

Problem statement :-
A Full Binary Tree is a binary tree where every node has either 0 or 2 children

It is not possible to construct a general Binary Tree from preorder and postorder traversals (See this). But if know that the Binary Tree is Full, we can construct the tree without ambiguity. Let us understand this with the help of following example.

Let us consider the two given arrays as pre[] = {1, 2, 4, 8, 9, 5, 3, 6, 7} and post[] = {8, 9, 4, 5, 2, 6, 7, 3, 1};
In pre[], the leftmost element is root of tree. Since the tree is full and array size is more than 1. The value next to 1 in pre[], must be left child of root. So we know 1 is root and 2 is left child. How to find the all nodes in left subtree? We know 2 is root of all nodes in left subtree. All nodes before 2 in post[] must be in left subtree. Now we know 1 is root, elements {8, 9, 4, 5, 2} are in left subtree, and the elements {6, 7, 3} are in right subtree.


                  1
                /   \
               /      \
     {8, 9, 4, 5, 2}     {6, 7, 3}
We recursively follow the above approach and get the following tree.

          1
        /   \
      2       3
    /  \     /  \
   4    5   6    7
  / \  
 8   9 


My Java implementation

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

class TreeNode {
  
    // data members
 public int key;
 public char charkey;
    public TreeNode left;
    public TreeNode right;
  
    // Constructor
    public TreeNode(int key) { this.key = key; left = null; right = null; }
    public TreeNode(char charkey) { this.charkey = charkey; left = null; right = null; }
  
    // Methods to set left and right subtrees
    public void setLeft(TreeNode left)   { this.left = left; }
    public void setRight(TreeNode right) { this.right = right; }
    
    public static void printLevelOrder(TreeNode root)
    {
      Queue<TreeNode> queue = new LinkedBlockingQueue<TreeNode>(); 
      
      while(root != null){
       System.out.println(root.charkey);
       if(root.left!=null){
        queue.add(root.left);
       }
       if(root.right!=null){
        queue.add(root.right);
       }
       root = queue.poll();
      }
    }
}



 public class ConstructTreeFromTraversal {
  
   int preOrderIndex=0;
   String inorder, preorder ,postorder;
  
 
 public static void main(String[] args) {
/* postorder preorder  test */
ConstructTreeFromTraversal obj = new ConstructTreeFromTraversal();
obj.postorder="894526731";
obj.preorder="124895367";
TreeNode root = obj.constructTree_Preorder_Postorder();
TreeNode.printLevelOrder(root);
System.out.println("Done");
}
 public TreeNode constructTree_Preorder_Postorder(){
return constructTree_Preorder_Postorder_inernal(postorder);
}
public TreeNode constructTree_Preorder_Postorder_inernal(String postorder){

if(postorder.equals("")){
return null;
}
// preOrderIndex which is initialized as zero indicates current position in preorder
// that is to be considered as root
char rootKey = preorder.charAt(preOrderIndex);
preOrderIndex++;
TreeNode root = new TreeNode(rootKey);
if(postorder.length()>1){
// In post-order last element will be root. So we will omit it for further process
// And split the string into two parts based on left child
String tempStringWithoutRoot = postorder.substring(0,postorder.length()-1);
char leftChildKEy = preorder.charAt(preOrderIndex);
if(tempStringWithoutRoot.length()>1){
String [] child = tempStringWithoutRoot.split(leftChildKEy+"");
TreeNode leftChild = constructTree_Preorder_Postorder_inernal(child[0]+leftChildKEy);
root.setLeft(leftChild);
if(child.length>1){
TreeNode rightChild = constructTree_Preorder_Postorder_inernal(child[1]);
root.setRight(rightChild);
}
}else{
TreeNode leftChild = constructTree_Preorder_Postorder_inernal(tempStringWithoutRoot);
}
}
return root;
}
}

Output

1
2
3
4
5
6
7
8
9
Done


Construct tree from inorder and preorder traversal

Reference :-
http://www.geeksforgeeks.org/construct-tree-from-given-inorder-and-preorder-traversal/

Problem Statement :-
Construct binary tree from inorder and preorder traversal
Let us consider the below traversals:

Inorder sequence: D B E A F C
Preorder sequence: A B D E C F

In a Preorder sequence, leftmost element is the root of the tree. So we know ‘A’ is root for given sequences. By searching ‘A’ in Inorder sequence, we can find out all elements on left side of ‘A’ are in left subtree and elements on right are in right subtree. So we know below structure now.

                 A
               /   \
             /       \
           D B E     F C
We recursively follow above steps and get the following tree.

         A
       /   \
     /       \
    B         C
   / \        /
 /     \    /
D       E  F
Algorithm: buildTree()
1) Pick an element from Preorder. Increment a Preorder Index Variable (preIndex in below code) to pick next element in next recursive call.
2) Create a new tree node tNode with the data as picked element.
3) Find the picked element’s index in Inorder. Let the index be inIndex.
4) Call buildTree for elements before inIndex and make the built tree as left subtree of tNode.
5) Call buildTree for elements after inIndex and make the built tree as right subtree of tNode.
6) return tNode.

My java implementation :-

import java.util.ArrayList;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

class TreeNode {
  
    // data members
public int key;
public char charkey;
    public TreeNode left;
    public TreeNode right;
  
    // Constructor
    public TreeNode(int key) { this.key = key; left = null; right = null; }
    public TreeNode(char charkey) { this.charkey = charkey; left = null; right = null; }
  
    // Methods to set left and right subtrees
    public void setLeft(TreeNode left)   { this.left = left; }
    public void setRight(TreeNode right) { this.right = right; }
    
    public static void printLevelOrder(TreeNode root)
    {
      Queue<TreeNode> queue = new LinkedBlockingQueue<TreeNode>(); 
      
      while(root != null){
     System.out.println(root.charkey);
     if(root.left!=null){
     queue.add(root.left);
     }
     if(root.right!=null){
     queue.add(root.right);
     }
     root = queue.poll();
      }
    }
}


 class ConstructTreeFromTraversal {
 
int preOrderIndex=0;
String inorder, preorder;

public static void main(String[] args) {

ConstructTreeFromTraversal obj = new ConstructTreeFromTraversal();
obj.inorder="DBEAFC";
obj.preorder="ABDECF";
TreeNode root = obj.constructTree();
System.out.println("Printing Level order traversal");
TreeNode.printLevelOrder(root);
System.out.println("Done");
}

public TreeNode constructTree(){
TreeNode root = constructTree_internal(inorder);
return root;

}
public TreeNode constructTree_internal(String inorder){
if(inorder.equals("")){
return null;
}
// preOrderIndex which is initialized as zero indicates current position in preorder
// that is to be considered as root
char rootKey = preorder.charAt(preOrderIndex);
preOrderIndex++;
TreeNode root = new TreeNode(rootKey);
// See it length of inorder is more than 1 i.e. it has node other than root
if(inorder.length()>1){
// Find rootKey in inOrder and split it into two parts
String [] child = inorder.split(rootKey+"");
try{
TreeNode leftChild = constructTree_internal(child[0]);
root.setLeft(leftChild);
// Call if right nodes are present
if(child.length>1){
TreeNode rightChild = constructTree_internal(child[1]);
root.setRight(rightChild);
}
}catch (Exception e){
e.printStackTrace();
}
}
return root;
}

}


Output

Printing Level order traversal
A
B
C
D
E
F
Done