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;
}
root.setRight
似乎是错误的。offset不应为offset+i
,而应为offset+i+1
:
root.setRight(buildInorderPostorder(post, n-1, offset+i+1,indexMap,n-1-i));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.