一只一棵二叉树的所有节点的值都不相同,给定这棵树的先序和中序遍历序列,重构二叉树
过程如下:
- 先序数组中最左边的值就是树的头节点值,记为h,并用h生成头节点,记为head,然后在中序数组中找到h,假设位置是i,那么在中序数组中,i左边的数组就是头节点左子树的中序数组,假设长度为l,则左子树的先序数组就是先序数组中h往右长度也为l的数组。
- 用左子树的先序和中序数组,递归整个过程建立左子树,返回的头节点记为left。
- i右边的数组就是头节点右子树的中序数组,假设长度为r,先序数组中右侧等长的部分就是头节点右子树的先序数组。
- 用右子树的先序和中序数组,递归整个过程建立右子树,返回的头节点记为right。
- 把head的左孩子和右孩子分别设置left和right,返回head,过程结束。
具体代码如下:
public TreeNode preInToTree(int[] pre, int[] in) {
if (pre == null || in == null) {
return null;
}
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < in.length; i++) {
map.put(in[i], i);
}
return preIn(pre, 0, pre.length - 1, in, 0, in.length - 1, map);
}
public TreeNode preIn(int[] p, int pi, int pj, int[] n, int ni, int nj, HashMap<Integer, Integer> map) {
if (pi > pj) {
return null;
}
TreeNode head = new TreeNode(p[pi]);
int index = map.get(p[pi]);
head.left = preIn(p, pi + 1, pi + index - ni, n, ni, index - 1, map);
head.right = preIn(p, pi + index - ni + 1, pj, n, index + 1, ni, map);
return head;
}