|
| 1 | +public class Solution { |
| 2 | + |
| 3 | + public static BinaryTreeNode<Integer> buildTree(int[] postOrder, int[] inOrder) { |
| 4 | + //Your code goes here |
| 5 | + BinaryTreeNode<Integer> root = buildTree(postOrder, inOrder, 0 ,postOrder.length-1, 0, inOrder.length-1); |
| 6 | + return root; |
| 7 | + } |
| 8 | + |
| 9 | + public static BinaryTreeNode<Integer> buildTree(int[] postOrder, int[] inOrder,int siPost, int eiPost, int siIn, int eiIn) { |
| 10 | + // TODO Auto-generated method stub |
| 11 | + |
| 12 | + //Base case - If number of elements in the post-order is 0 |
| 13 | + if (siPost>eiPost) |
| 14 | + { |
| 15 | + return null; |
| 16 | + } |
| 17 | + |
| 18 | + //Defining the root node for current recursion |
| 19 | + int rootData=postOrder[eiPost]; |
| 20 | + BinaryTreeNode<Integer> root = new BinaryTreeNode<Integer>(rootData); |
| 21 | + |
| 22 | + //Finding root data's location in Inorder (Assuming root data exists in Inorder) |
| 23 | + int rootIndex=-1; |
| 24 | + for (int i=siIn;i<=eiIn;i++) |
| 25 | + { |
| 26 | + if (rootData==inOrder[i]) |
| 27 | + { |
| 28 | + rootIndex=i; |
| 29 | + break; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + //Defining index limits for Left Subtree Inorder |
| 34 | + int siInLeft=siIn; |
| 35 | + int eiInLeft=rootIndex-1; |
| 36 | + |
| 37 | + //Defining the index limits for Left Subtree Preorder |
| 38 | + int siPostLeft=siPost; |
| 39 | + int leftSubTreeLength = eiInLeft - siInLeft + 1; |
| 40 | + int eiPostLeft=(siPostLeft)+(leftSubTreeLength-1); |
| 41 | + |
| 42 | + //Defining index limits for Right Subtree Inorder |
| 43 | + int siInRight=rootIndex+1; |
| 44 | + int eiInRight=eiIn; |
| 45 | + |
| 46 | + //Defining index limits for Right Subtree Preorder |
| 47 | + int siPostRight=eiPostLeft+1; |
| 48 | + int eiPostRight=eiPost-1; |
| 49 | + |
| 50 | + BinaryTreeNode<Integer> rightChild = buildTree(postOrder, inOrder, siPostRight, eiPostRight, siInRight, eiInRight); |
| 51 | + BinaryTreeNode<Integer> leftChild = buildTree(postOrder, inOrder, siPostLeft, eiPostLeft, siInLeft, eiInLeft); |
| 52 | + |
| 53 | + root.left=leftChild; |
| 54 | + root.right=rightChild; |
| 55 | + return root; |
| 56 | + } |
| 57 | + |
| 58 | + |
| 59 | + |
| 60 | +} |
0 commit comments