Construct Binary Tree from Inorder and Postorder Traversal

public class Solution {

public TreeNode buildTree(int[] inorder, int[] postorder) {

return buildTree(inorder,postorder,0,inorder.length-1,postorder.length-1);

}

public TreeNode buildTree(int[] inorder, int[] postorder, int l, int h, int p){

if(l>h) return null;

TreeNode root= new TreeNode(postorder[p]);

int i;

for(i=l;i<=h;i++){

if(inorder[i]==postorder[p])

break;

}

root.left=buildTree(inorder,postorder,l,i-1,p-1-(h-i));

root.right=buildTree(inorder,postorder,i+1,h,p-1);

return root;

}

}

Last updated

Was this helpful?