http://www.lintcode.com/en/problem/construct-binary-tree-from-inorder-and-postorder-traversal/
中序和后序遍历生成二叉树
套路题,要熟练!!
边界情况先写 + 不能用二分(因为不是有序序列)
public class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
// write your code here
return buildTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
}
public TreeNode buildTree(int[] inorder, int bin, int ein, int[] postorder,
int bpo, int epo) {
// 边界情况首先就写上啊!!!!
if (bin == ein) {
return new TreeNode(inorder[bin]);
} else if (bin > ein) {
return null;
}
TreeNode root = new TreeNode(postorder[epo]);
int index = 0;
for (int i = bin; i <= ein; i++) {
if (inorder[i] == postorder[epo]) {
index = i;
break;
}
}
root.left = buildTree(inorder, bin, index - 1, postorder, bpo, bpo + index - 1 - bin);
root.right = buildTree(inorder, index + 1, ein, postorder, bpo + index - bin, epo - 1);
return root;
}
}