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 rebuildTree(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[end - rootIndex]) {
break;
}
rootIndex++;
}
// System.out.println("rootIndex = " + rootIndex);
// 如果遍历inv结束都没有找到与pre[0]相等的值,则不能重构二叉树
if (rootIndex >= length) {
CanReBuild = false;
return null;
}
// 建立子树的左子树
root.lchild = rebuildTree(preOrder, start + 1, inOrder, end - rootIndex
- 1, length - 1 - rootIndex);
// 建立子树的右子树
root.rchild = rebuildTree(preOrder, start + length - rootIndex,
inOrder, end, rootIndex);
return root;
}
// 根据前序遍历和中序遍历重构二叉树
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;
}
}
Java实现二叉树重构
最新推荐文章于 2023-11-29 10:13:19 发布