根据先序及中序遍历结果创建树,java实现
来源:互联网 发布:私人淘宝3c认证怎么弄 编辑:程序博客网 时间:2024/06/11 09:35
仓促写完的,初步测试时正确的,还不确定有没有bug,记录一下。
class BinaryTree
{public int data;
public BinaryTree lChild;
public BinaryTree rChild;
}
public class CreateTree
{
public static void postTraverse(BinaryTree bTree)
{
if (bTree.lChild == null && bTree.rChild == null)
{
System.out.println(bTree.data);
return;
}
if (bTree.lChild != null)
{
postTraverse(bTree.lChild);
}
if (bTree.rChild != null)
{
postTraverse(bTree.rChild);
}
System.out.println(bTree.data);
}
public static BinaryTree createTree(int[] preArray, int[] inArray)
{
if (preArray != null && preArray.length == 1)
{
int value = preArray[0];
BinaryTree node = new BinaryTree();
node.data = value;
node.lChild = null;
node.rChild = null;
return node;
}
if (preArray == null)
{
return null;
}
int rootValue = preArray[0];
BinaryTree rootNode = new BinaryTree();
rootNode.data = rootValue;
int i;
for (i = 0; i < inArray.length; ++i)
{
if (rootValue == inArray[i])
{
break;
}
}
int lLength = i;
int rLength = preArray.length - 1 - lLength;
int[] lPreArray = null;
int[] lInArray = null;
int[] rPreArray = null;
int[] rInArray = null;
if (lLength > 0)
{
lPreArray = new int[lLength];
lInArray = new int[lLength];
for (int j = 0; j < lLength; ++j)
{
lPreArray[j] = preArray[j + 1];
lInArray[j] = inArray[j];
}
}
else if (lLength == 0)
{
rootNode.lChild = null;
}
if (rLength > 0)
{
rPreArray = new int[rLength];
rInArray = new int[rLength];
for (int j = 0; j < rLength; ++j)
{
int originIndex = j + 1 + i;
rPreArray[j] = preArray[originIndex];
rInArray[j] = inArray[originIndex];
}
}
else if (rLength == 0)
{
rootNode.rChild = null;
}
rootNode.lChild = createTree(lPreArray, lInArray);
rootNode.rChild = createTree(rPreArray, rInArray);
return rootNode;
}
public static void main(String[] args)
{
int[] preArray =
{ 1, 2, 4, 7, 3, 5, 6, 8 };
int[] inArray =
{ 4, 7, 2, 1, 5, 3, 8, 6 };
BinaryTree bTree = createTree(preArray, inArray);
postTraverse(bTree);
}
}
- 根据先序及中序遍历结果创建树,java实现
- Java实现——根据先序遍历和中序遍历,确定二叉树
- 数据结构--java实现二叉树的先序、中序、后序、层次遍历及根据先序中序建立二叉树
- 根据中序遍历和先序遍历,后序遍历创建二叉树。
- 根据先序和中序遍历重建二叉树java实现
- 根据二叉树的先序、中序遍历结果重建二叉树
- 根据二叉树的先序、中序遍历结果重建二叉树
- 根据二叉树的先序、中序遍历结果重建二叉树
- 面试题3:根据先序和中序遍历的结果构建二叉树
- 根据先序和中序遍历结果画出二叉树
- 根据先序遍历和中序遍历结果求后续遍历模板
- 二叉树的创建(先序创建的)及先序遍历 中序遍历 后序遍历的递归和非递归实现
- 根据先序遍历和中序遍历创建二叉树
- 根据先序遍历和中序遍历创建二叉树
- 数组实现根据二叉树的先序遍历和中序遍历构造二叉树
- C++ 二叉树实现 创建,先序遍历,中序遍历,后序遍历
- 剑指offer--重建二叉树[根据二叉树的先序、中序遍历结果重建二叉树]
- 根据先序和中序遍历重建二叉树
- Unity3D性能优化
- PHP5 在调用 JAVA WebService 时遇到的各种问题及解决方法(一)
- HBase入门篇2-Java操作HBase例子
- quest3d q.LoadChannelGroupDQ的详解
- SpringMVC数据绑定使用指南
- 根据先序及中序遍历结果创建树,java实现
- 使用ubuntu PC开发ARM单板常用技巧总结
- MapXtreme多边形有关的方法
- map
- git下push失败解决方法
- ftp 命令行下载上传数据
- LLVM CLANG 3.1 GCC 4.7 INTEL CORE I7 BENCHMARKS
- 下载chrome插件和离线安装CRX文件的方法
- 浅学设计模式之迭代器<Iterator>模式