二叉树构建(一)

来源:互联网 发布:php磁力链接解析接口 编辑:程序博客网 时间:2024/04/29 00:00

说明:

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 0
原创粉丝点击