1、题目描述
https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
2、解法
有了前一道题的经验加成,我们可以很容易的写出下面的代码:
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
return build(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
}
//postorder后序序列,inorder后序序列,posStart,posEnd,inStart,inEnd都是对应索引
public TreeNode build(int[]inorder,int inStart,int inEnd,int[]postorder,int posStart,int posEnd){
if(posStart>posEnd) return null;
//构建根节点,根节点是后序遍历的最后一个节点
TreeNode root = new TreeNode(postorder[posEnd]);
int root_index = 0;//1个元素
//寻找中序遍历的根节点索引,从而获得左子树的节点个数和右子树的节点个数
for(int i=inStart;i<=inEnd;i++){
if(inorder[i]==root.val){
root_index = i;
break;
}
}
int left_size = root_index-inStart;//左子树节点个数 root_index-inStart+1-1=root_index-inStart
//构建左子树,注意下标
root.left = build(inorder,inStart,root_index-1,postorder,posStart,posStart+left_size-1);
//构建右子树
root.right = build(inorder,root_index+1,inEnd,postorder,posStart+left_size,posEnd-1);
return root;
}
}