根据中序遍历和后序遍历树构造二叉树
给出树的中序遍历: [1,2,3] 和后序遍历: [1,3,2]
返回如下的树:
2
/ \
1 3
**规则**
输入:两个数组 int a[] 和 int b[]
输出:头结点Head
case:
```
数组为null或length为0
两个数组长度不一致,内容不同
只有一个元素
只有两个元素
都在左侧
都在右侧
两边都有
```
**思路**
对一个实例`[4,7,2,1,5,3,8,6][7,4,2,5,8,6,3,1]`进行分析后,可以得出这样的规则
```
b[len-1]为头节点,该节点为1,在pre中查找1的位置为pos=3,从pos=3开始,共3个元素为左边子树,4-end为右边子树
设每次数组有范围ae~ab be-bb mid为post[bb-1]在pre中的位置
左 ab = ab ae = mid-1 bb = bb be = bb+(mid-1-ab) (be-bb = ae -ab)
右 ab = mid+1 ae=ae bb=(be-1)-(ae-mid-1) be=be-1
其中,ae不能大于ab be不能大于bb 否则返回null
```
**代码**
```
public class Solution {
/*
* @param inorder: A list of integers that inorder traversal of a tree
* @param postorder: A list of integers that postorder traversal of a tree
* @return: Root of a tree
*/
public TreeNode buildTree(int[] preorder, int[] postorder) {
if(preorder == null || postorder == null) {return null;}
if(preorder.length * postorder.length == 0) {return null;}
if(preorder.length != postorder.length) {return null;}
return buildTree(preorder,0,preorder.length-1,postorder,0,postorder.length-1);
}
private TreeNode buildTree (int[] pre,int ab,int ae, int[] post,int bb,int be) {
if(ab > ae || bb > be) return null;
int p = post[be],mid = 0;
for ( mid = ab; mid <= ae; mid++) {
if(pre[mid] == p) {
break;
}
}
// FIND MID
TreeNode node = new TreeNode(p);
node.left = buildTree(pre,ab,mid-1,post,bb,bb+(mid-1-ab+1)-1);
node.right = buildTree(pre,mid+1,ae, post,(be-1)-(ae-mid-1),be-1);
return node;
}
}
```