版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jun8148/article/details/85247192
9. 重建二叉树
问题描述:
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树,假设输入的前序遍历和终须遍历的结果中都不包含重复的数字。
例如:
前序遍历序列{1, 2, 4, 7, 3, 5, 6, 8};
中序遍历序列{4, 7, 2, 1, 5, 3, 8, 6};
二叉树节点定义如下:
public static class Node {
public int value;
public Node left;
public Node right;
}
分析:
- 前序遍历,先访问根节点,在依次访问左右子节点
- 中序遍历,先访问左子节点,在访问根节点,在访问右子节点
- 按照上面的说法,前序遍历的第一个数就是根节点
- 继续我们遍历中序序列,找到这个数的位置,它的左边就是这个根节点的左边节点,右边就是这个根节点的右边节点
- 接着我们构造新的序列,重复3,4步骤
按照上面的分析,我们先构造出二叉树的图:
前序遍历的第一个数字 1 就是根节点的值,由此构建出 1 这个节点,再扫描中序序列,得到根节点的位置 [3] , 这个时候,可以得到,从根节点开始,有3个数字都是左子树的节点,位于1后面的都是右子树节点,
新的前序遍历序列就是{2, 4, 7},中序遍历数列就是{4, 7, 2},重复上面的步骤,直到把左子树构建完,再来构建右子树。
代码如下:
/**
* Class day09 ...
*
* @author LiJun
* Created on 2018/12/24
*
*/
// 输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树,
// 假设输入的前序遍历和终须遍历的结果中都不包含重复的数字。
// 例如:
// 前序遍历序列{1, 2, 4, 7, 3, 5, 6, 8};
// 中序遍历序列{4, 7, 2, 1, 5, 3, 8, 6};
public class day09 {
public static class Node {
public int value;
public Node left;
public Node right;
}
public static Node Construct(int[] preOrder, int[] inOrder) {
// 参数有效性检查
if (preOrder == null || inOrder == null || preOrder.length <= 0
|| inOrder.length <= 0 || preOrder.length != inOrder.length) {
return null;
}
return ConstructCore(preOrder, 0, preOrder.length - 1,
inOrder, 0, inOrder.length - 1);
}
public static Node ConstructCore(int[] preOrder, int startPre,
int endPre, int[] inOrder, int startIn, int endIn) {
if (startPre > endPre)
return null;
int index;
for (index = startIn; index <= endIn &&
inOrder[index] != preOrder[startPre]; index++) ;
Node root = new Node();
root.value = preOrder[startPre];
root.left = ConstructCore(
preOrder, startPre + 1, startPre + index - startIn,
inOrder, startIn, index - 1);
root.right = ConstructCore(preOrder, startPre + index + 1 - startIn,
endPre, inOrder, index + 1, endIn);
return root;
}
public static void printPre(Node tNode) {
if (tNode != null) {
System.out.print(tNode.value + " ");
printPre(tNode.left);
printPre(tNode.right);
}
}
public static void printIn(Node tNode) {
if (tNode != null) {
printIn(tNode.left);
System.out.print(tNode.value + " ");
printIn(tNode.right);
}
}
public static void main(String[] args) {
int[] preOrder = {1, 2, 4, 7, 3, 5, 6, 8};
int[] inOrder = {4, 7, 2, 1, 5, 3, 8, 6};
Node construct = Construct(preOrder, inOrder);
printPre(construct);
System.out.println();
printIn(construct);
}
}
当然我是用递归实现的,你们可以尝试改成迭代方法。在这只是提供思路。