题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
先定义一个二叉树类TreeNode
package com.jason.algorithm;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
具体实现方法如下:
package com.jason.algorithm;
import java.util.HashMap;
public class Solution {
public static void main(String[] args) {
int pre[] = { 1, 2, 4, 7, 3, 5, 6, 8 };
int in[] = { 4, 7, 2, 1, 5, 3, 8, 6 };
Solution solution = new Solution();
solution.reConstructBinaryTree(pre, in);
}
public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
if (pre == null || in == null) {
return null;
}
HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
for (int i = 0; i < in.length; i++) {
hashMap.put(in[i], i);
}
return preIn(pre, 0, pre.length - 1, in, 0, in.length - 1, hashMap);
}
// {1,2,4,7,3,5,6,8} pre 根左右
// {4,7,2,1,5,3,8,6} in 左根右
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, nj, map);
System.out
.println("head =" + (head != null ? head.val : " ")
+ " head.left ="
+ (head.left != null ? head.left.val : " ")
+ " head.right ="
+ (head.right != null ? head.right.val : " "));
return head;
}
}