// inorder 1 2 3 | 4 | 5 6 7
// postorder 1 3 2 | 5 7 6 | 4
public class Solution {
private int findPosition(int[] arr, int start, int end, int target) {
int i;
for (i = start; i <= end; i++) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
private TreeNode buildHelper(int[] inorder, int instart, int inend,
int[] postorder, int poststart, int postend) {
if (instart > inend) {
return null;
}
TreeNode root = new TreeNode(postorder[postend]);
int position = findPosition(inorder, instart, inend, postorder[postend]);
// poststart + (position - instart) - 1
// 这是计算在调用向左递归时,在postorder中的右边界
// postorder的右边界怎么确定?
// 先从postoder的结构去看,左边一半是左子树,右边一半是右子树,最后一个是 mid
// 计算向左递归的边界就是看左半边(左子树)有几个
// 左子树有几个,这个问题是可以从inorder看出来的,inorder的已经找到了position这个值,这个值左边的就都是左子树
root.left = buildHelper(inorder, instart, position - 1,
postorder, poststart, poststart + (position - instart) - 1);
// 同上面的分析,找到像右递归时的左边界
root.right = buildHelper(inorder, position + 1, inend,
postorder, postend - (inend - position), postend);
return root;
}
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (inorder == null || postorder == null || inorder.length == 0 || postorder.length == 0) {
return null;
}
if (inorder.length != postorder.length) {
return null;
}
return buildHelper(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
}
Construct Binary Tree from Inorder and Postorder Traversal
最新推荐文章于 2021-02-03 15:56:42 发布