通常二叉树重构都可以有先序遍历序列和中序遍历序列重构,,当然在二叉树是满二叉树的情况下也可以通过先序和后序遍历序列重构,这里只针对前一种情况。
构建和遍历在前面有,这里只写了重构方法。
package com.tree;
public class RebuildBiTree {
static boolean CanReBuild = true; // 用来标示是否能够重构二叉树
public static void main(String[] args) {
int[] preorder = { 1, 2, 3, 4, 5 };
int[] inorder = { 3, 2, 4, 1, 5 };
BitNode proot = rebuildTree2(preorder, 0, inorder, inorder.length - 1,
inorder.length);
if (CanReBuild)
BinTree.PostOrderTraverse(proot);//后序遍历
}
// 根据前序遍历和中序遍历重构二叉树
public static BitNode rebuildTree2(int[] preOrder, int start,
int[] inOrder, int end, int length) {
// 参数验证
if (preOrder == null || preOrder.length == 0 || inOrder == null
|| inOrder.length == 0 || length <= 0) {
CanReBuild = false;
return null;
}
// 建立子树根节点
int value = preOrder[start];
BitNode root = new BitNode();
root.data = value;
// 递归终止条件:子树只有一个节点
if (length == 1)
return root;
// 根据根节点分拆中序序列中 左子树和右子树
int rootIndex = 0;// 中序中根节点倒序位置
while (rootIndex < length) {
if (value == inOrder[rootIndex]) {
break;
}
rootIndex++;
}
// System.out.println("rootIndex = " + rootIndex);
// 如果在中序遍历中没有找到根节点,则无法重构
if (rootIndex >= length) {
CanReBuild = false;
return null;
}
// 建立子树的左子树
root.lchild = rebuildTree(preOrder, start + 1, inOrder, rootIndex
- 1, rootIndex);
// 建立子树的右子树
root.rchild = rebuildTree(preOrder, rootIndex + 1,
inOrder, end, length - rootIndex - 1);
return root;
}
}
打印:
3 4 2 5 1