[GeeksForGeeks] Get postorder traversal sequence from given inorder and preorder traversal.
Given Inorder and Preorder traversals of a binary tree, print Postorder traversal.
Example:
Input: Inorder traversal in[] = {4, 2, 5, 1, 3, 6} Preorder traversal pre[] = {1, 2, 4, 5, 3, 6} Output: Postorder traversal is {4, 5, 2, 6, 3, 1}
A naive solution is to first construct the given tree, then recursively traverse it in post order.
A better solution is to acheive this without having to construct the given tree first.
1 import java.util.ArrayList; 2 3 public class getPostorder { 4 public ArrayList<Integer> getPostorderSeq(int[] in, int[] pre) { 5 if(in == null || pre == null || in.length != pre.length || in.length == 0) { 6 return null; 7 } 8 ArrayList<Integer> post = new ArrayList<Integer>(); 9 helper(in, 0, in.length - 1, pre, 0, pre.length - 1, post); 10 return post; 11 } 12 private void helper(int[] in, int in_start, int in_end, 13 int[] pre, int pre_start, int pre_end, 14 ArrayList<Integer> post) { 15 if(in_start > in_end) { 16 return; 17 } 18 int rootIdx = pre_start; 19 int inOrderRootIdx = in_start; 20 for(; inOrderRootIdx <= in_end; inOrderRootIdx++) { 21 if(pre[rootIdx] == in[inOrderRootIdx]) { 22 break; 23 } 24 } 25 helper(in, in_start, inOrderRootIdx - 1, pre, pre_start + 1, pre_start + inOrderRootIdx - in_start, post); 26 helper(in, inOrderRootIdx + 1, in_end, pre, pre_end - in_end + inOrderRootIdx + 1, pre_end, post); 27 post.add(pre[rootIdx]); 28 } 29 }