根据前序遍历和中序遍历树构造二叉树.
样例
给出中序遍历:[1,2,3]
和前序遍历:[2,1,3]
. 返回如下的树:
2
/ \
1 3
思路:
前序: 2 1 4 5 3 6
中序: 4 1 5 2 6 3
首先根据前序的第一个元素可知 根节点为2, 然后在中序中寻找2, 然后在2之前的元素就
可知是 左子树的元素,那么左子树的元素个数就知道了。 然后左右子树的 前序, 中序 都可知了,
最后递归即可。
Java代码:
public static TreeNode buildTree_run(int[] inorder, int[] postorder) {
// write your code here
if(inorder.length!=postorder.length){
return null;
}
return build(inorder, 0, inorder.length-1, postorder, 0, postorder.length);
}
public TreeNode build(int[] inorder, int inpre, int inlast, int[] postorder, int postpre, int postlast){
if(inpre>inlast){return null; }
// 先找到根节点
TreeNode node = new TreeNode(postorder[postpre]);
// 在中序中找到根的位置
int i = inpre;
for(;i<=inlast;i++){
if(inorder[i] == postorder[postpre]){break;}
}
node.left = build(inorder, inpre, i-1, postorder, postpre+1, postpre+i-inpre);
node.right = build(inorder, i+1, inlast, postorder, postpre+i-inpre+1, postlast);
return node;
}