二叉树构建(一)

说明:

1.根据先序遍历和中序遍历或者后序遍历和中序遍历可以构建一棵二叉树;

2.构建以后序遍历和中序遍历为例,结点数据域以整形为例。

定义二叉树类

核心是constractPostCore函数。

class BinaryTree{
	
	private BinaryTreeNode root;
	
	static class BinaryTreeNode{
		 int value;
	 	 BinaryTreeNode left;
		 BinaryTreeNode right;
		 BinaryTreeNode(int value){
			 this(value, null, null);
		 }
		 BinaryTreeNode(int value, BinaryTreeNode left, BinaryTreeNode right){
			 this.value = value;
			 this.left = left;
			 this.right = right;
		 }
	}
	public BinaryTree(int[] postOrder, int[] inOrder){
		int postLen = 0;
		int inLen = 0;
		if(postOrder == null ||(postLen = postOrder.length) == 0){
			throw new IllegalArgumentException();
		}
		if(inOrder == null || (inLen = inOrder.length) == 0){
			throw new IllegalArgumentException();
		}
		this.root = this.constractPostCore(postOrder, 0, postLen -1, inOrder, 0, inLen - 1);
	}
	private BinaryTreeNode constractPostCore(int[] postOrder, int postBegin, int postEnd, int[] inOrder, int inBegin, int inEnd){
		  // may be leftLen <= 0 or rightLen <= 0 
		  if(postBegin > postEnd || inBegin > inEnd){
			  return null;
		  }
		  // this a leaf node or may be throw exception
		  boolean isLeafOrException = ((postBegin == postEnd) && (inBegin == inEnd));
		  if(isLeafOrException){
			  boolean isException = (postOrder[postBegin] != inOrder[inBegin]);
			  if(isException) throw new IllegalArgumentException();
			  return new BinaryTreeNode(postOrder[postEnd],null,null);
		  }
		  // other situation postBegin < postEnd && inBegin < inEnd
		  int rootValue = postOrder[postEnd];
		  BinaryTreeNode currentRoot = new BinaryTreeNode(rootValue, null, null);
		  int rootPositionInOrder = this.getRootPositionInOrder(inOrder, inBegin, inEnd, rootValue);
		  boolean isFound = (rootPositionInOrder != -1);
		  if(isFound){
			  // leftTreeLen may be negative but do not need to 
			  //check because that at the begin will be checked
			  int leftTreeLen = rootPositionInOrder - inBegin;
			  // rightTreeLen is the same as leftTreeLen may be negative
			  int rightTreeLen = inEnd - rootPositionInOrder;
			  currentRoot.left = this.constractPostCore(postOrder, postBegin, postBegin + leftTreeLen - 1, inOrder, inBegin, rootPositionInOrder - 1);
			  currentRoot.right = this.constractPostCore(postOrder, postEnd - rightTreeLen, postEnd - 1, inOrder, rootPositionInOrder + 1, inEnd);			  
		  }else{
			  throw new IllegalArgumentException("currentValue not found in inOrder" + rootValue);
		  }
		  return currentRoot;
		  
	}
	private int getRootPositionInOrder(int[] inOrder, int inBegin , int inEnd, int value){
		 for(int i = inBegin; i <= inEnd; i++){
			 if(inOrder[i] == value){
				 return i;
			 }
		 }
		 return -1;
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值