题目:根据前序,中序重建二叉树
- 前序: 1 2 4 7 3 5 6 8
- 中序: 4 7 2 1 5 3 8 6
解析
- 前序: 根左右 中序:左根右 后序:左右根
- 由此可知:根节点为1,由中序可知左子树为472,右子树为5386
- 由上面的分析可继续得出递归结果:例如只是左子树
| 序号 |
根节点 |
左子树 |
右子树 |
| 1 |
1 |
前序: 1 2 4 7 ,中序:4 7 2 1 |
前序: 3 5 6 8 ,中序:5 3 8 6 |
| 2 |
2 |
前序: 2 4 7 ,中序:4 7 2 |
无 |
| 3 |
4 |
无 |
前序: 4 7 ,中序: 4 7 |
- java实现:
/**
* 已知 :
* 前序: 1 2 4 7 3 5 6 8
* 中序: 4 7 2 1 5 3 8 6
*/
/**
* Definition for binary tree
*/
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
@Override
public String toString() {
return "TreeNode{" +
"val=" + val +
", left=" + left +
", right=" + right +
'}';
}
}
public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
TreeNode rootNode = new TreeNode(pre[0]);
reConstruct(rootNode, pre, in);
return rootNode;
}
public void reConstruct(TreeNode rootNode, int[] pre, int[] in) {
//根节点
int root = pre[0];
//查找左节点 和 右节点
//根节点所在位置
int inRoot = 0;
for (int i = 0; i < in.length; i++) {
if (in[i] == root) {
inRoot = i;
}
}
//左子树
if (inRoot > 0) {
//中序
int[] inVo = new int[inRoot];
System.arraycopy(in, 0, inVo, 0, inRoot);
//前序
int[] preVo = new int[inRoot];
System.arraycopy(pre, 1, preVo, 0, inRoot);
rootNode.left = new TreeNode(preVo[0]);
reConstruct(rootNode.left, preVo, inVo);
}
//右子树
if (inRoot < in.length - 1) {
//中序
int[] inVo = new int[in.length - inRoot - 1];
System.arraycopy(in, inRoot + 1, inVo, 0, in.length - inRoot - 1);
//前序
int[] preVo = new int[in.length - inRoot - 1];
System.arraycopy(pre, inRoot + 1, preVo, 0, in.length - inRoot - 1);
rootNode.right = new TreeNode(preVo[0]);
reConstruct(rootNode.right, preVo, inVo);
}
}
@Test
public void test1() {
System.out.println(reConstructBinaryTree(new int[]{1, 2, 4, 7, 3, 5, 6, 8}, new int[]{4, 7, 2, 1, 5, 3, 8, 6}));
}