0

I was trying to familarize with the question of creating a tree given inorder and postorder traversal. I wrote the following code, but some thing is going wrong which i was unable to find out. Can someone help me on this?

Sample i/p :

int in[] = {4,10,3,1,7,11,8,2}; int post[] = {4,1,3,10,11,8,2,7};

public static TreeNode buildInorderPostorder( int post[], int n, int offset,Map<Integer,Integer> indexMap,int size) {     
      if (size <= 0) return null;
      int rootVal = post[n-1];
      int i = (indexMap.get(rootVal) - offset);
      TreeNode root = new TreeNode(rootVal);
      root.setLeft(buildInorderPostorder( post, i, offset,indexMap,i-offset));
      root.setRight(buildInorderPostorder(post, n-1, offset+i,indexMap,n-1-i));
      return root;
    }
user1643001
  • 207
  • 1
  • 2
  • 7

1 Answers1

0

root.setRight seems to be wrong.offset shouldn't be offset+i, it should be offset+i+1:

root.setRight(buildInorderPostorder(post, n-1, offset+i+1,indexMap,n-1-i));
Ritesh Kumar Gupta
  • 5,055
  • 7
  • 45
  • 71
  • I tried this, but still not working .public static TreeNode buildInorderPostorder( int post[], int n, int offset,Map indexMap,int size) { if (size <= 0) return null; int rootVal = post[n-1]; int i = (indexMap.get(rootVal) - offset); TreeNode root = new TreeNode(rootVal); root.setLeft(buildInorderPostorder( post, i, offset,indexMap,i-offset)); root.setRight(buildInorderPostorder(post, n-1, offset+i+1,indexMap,n-1-i)); return root; } – user1643001 Mar 26 '13 at 20:09
  • I am checking further error.Can you please post the entire program at ideone http://ideone.com/ and send us the link? – Ritesh Kumar Gupta Mar 26 '13 at 20:12