您的位置:首页 > 编程语言 > Java开发

Java实现由前序序列和中序序列重建二叉树,并后序输出。

2014-08-04 16:27 483 查看
具体实现采用递归方式,也可采用桟来模拟递归实现(读者可自己实现)。

/**
* 得知二叉树前序序列 中序序列构建二叉树 并后序输出
* @author gengtao
*
*/

/**
* 使用java中的类来模拟 结构体(c/c++ struct)
*
*/
class BinaryTree{
int value;
BinaryTree left;
BinaryTree right;
}

public class train0804 {

public static void main(String[] args) {
// TODO Auto-generated method stub
int[] preList = new int[]{1,2,4,7,3,5,6,8};
int[] inList = new int[]{4,7,2,1,5,3,8,6};
//		int[] preList = new int[]{1,2,4,7};
//        int[] inList = new int[]{4,7,2,1};
PostOrder(Construct(preList, inList, 8));
}

//构建二叉树
public static BinaryTree Construct(int[] preList , int[] inList , int length){
if(preList == null || inList == null || length <= 0){
return null;
}
return ConstructCore(preList , 0 , preList.length - 1 , inList , 0 , inList.length - 1 , length);
}
/**
*
* @param preList  前序数组
* @param preStart 前序索引起始位置
* @param preEnd   前序索引终止位置
* @param inList   中序数组
* @param inStart  中序索引起始位置
* @param inEnd    中序索引终止位置
* @param length   数组总长度
* @return
*/
public static BinaryTree ConstructCore(int[] preList , int preStart , int preEnd, int[] inList , int inStart , int inEnd , int length) {
//System.out.println(preStart+"==="+preEnd+"         "+inStart +"==========="+inEnd);
int rootValue = preList[preStart];
//System.out.println(rootValue);
BinaryTree root = new BinaryTree();
root.value = rootValue;
root.left = root.right = null;
if(preStart >= length || preEnd >= length || inStart >= length || inEnd >= length){
return null;
}
if(preList[preStart] == preList[preEnd]){
if(inList[inStart] == inList[inEnd]){
return root;
}else{
System.out.println("Invalid input.");
}
}
//在中序遍历中找到根节点的值
int rootInorder = inStart;
while(rootInorder <= inEnd && inList[rootInorder] != rootValue){
rootInorder ++;
}
if(rootInorder == inEnd && inList[rootInorder] != rootValue){
System.out.println("Invalid input.");
}
int leftLength = rootInorder - inStart;
int leftPreorderEnd = preStart + leftLength;
//构建左子树
if(leftLength > 0){
root.left = ConstructCore(preList, preStart + 1, leftPreorderEnd, inList, inStart, rootInorder - 1 , length);
}
//构建右子树
if(leftLength < preEnd - preStart){
root.right = ConstructCore(preList, leftPreorderEnd + 1, preEnd, inList, rootInorder + 1, inEnd , length);
}
return root;
}

//后序遍历二叉树
public static void PostOrder(BinaryTree bt){
if(bt != null){
PostOrder(bt.left);
PostOrder(bt.right);
System.out.print(bt.value + " ");
}
}
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐