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

具体实现采用递归方式,也可采用桟来模拟递归实现(读者可自己实现)。

/**
 * 得知二叉树前序序列 中序序列构建二叉树 并后序输出
 * @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 + " ");
		}
	}
}



                
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值