106-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal
0x0 题目详情
0x1 解题思路
0x2 代码实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(inorder==null || inorder.length==0 || postorder==null || postorder.length==0){
return null;
}
Map<Integer,Integer> indexMap=new HashMap<>();
for (int i=0;i<inorder.length;i++){
indexMap.put(inorder[i],i);
}
return recur(postorder,indexMap,postorder.length-1,-1,inorder.length-1,-1);
}
//所有区间采取左开右闭区间
private TreeNode recur(int[] postorder,Map<Integer,Integer> indexMap,int postBegin,int postEnd,int inBegin,int inEnd){
if(postBegin<=postEnd){
return null;
}
//先构建右子树,再构建左子树
TreeNode root=new TreeNode(postorder[postBegin]);
int pivot=indexMap.get(postorder[postBegin]);
//计算右子树长度
int rightLength=inBegin-pivot;
int leftLength=pivot-inEnd-1;
root.right=recur(postorder,indexMap,postBegin-1,postBegin-1-rightLength,inBegin,pivot);
root.left=recur(postorder,indexMap,postBegin-1-rightLength,postBegin-1-rightLength-leftLength,pivot-1,inEnd);
return root;
}
}0x3 课后总结
Last updated