利用前序遍历来构建Tree,然后通过后续遍历来检验当前树是否构建完毕。
/**
*
* 889. 根据前序和后序遍历构造二叉树
*
* 执行用时: 1 ms
* 内存消耗: 37.9 MB
*
*/
public class ConstructFromPrePost {
int preIdx = 0, postIdx = 0;
public TreeNode constructFromPrePost(int[] pre, int[] post) {
TreeNode node = new TreeNode(pre[preIdx++]);
if (node.val != post[postIdx]){
node.left = constructFromPrePost(pre, post);
}
if (node.val != post[postIdx]){
node.right = constructFromPrePost(pre, post);
}
postIdx++;
return node;
}
}