- 前中后序的遍历是指对一个二叉树而言,最终的遍历结果的根节点是在哪里的顺序,即
* 前序遍历:根节点、左子树、右子树
* 中序遍历:左子树、根节点、右子树
* 后序遍历:左子树、右子树、根节点
- 重建的思路:根据根节点位置找到根节点,例如前序的首位或者后续的末尾,然后在中序遍历中找到根节点的位置,借此划分出左右子树的子数组,然后进行递归重建
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length==0)return null;
if(preorder.length==1&&inorder.length==1){
return new TreeNode(preorder[0]);
}
TreeNode root = new TreeNode(preorder[0]);
int i;
for(i = 0 ;i<inorder.length;i++){
if(inorder[i]==preorder[0])break;
}
root.left = buildTree(Arrays.copyOfRange(preorder,1,1+i),Arrays.copyOfRange(inorder,0,i));
root.right = buildTree(Arrays.copyOfRange(preorder,i+1,preorder.length),Arrays.copyOfRange(inorder,i+1,inorder.length));
return root;
}