题目
输入某二叉树的前序遍历和中序遍历的结果,请重新构造出该二叉树。假设输入的前序遍历和中序遍历的结果中不包含重复的数字。例如输入的前序遍历序列为{1,2,4,7,3,5,6,8}和中序遍历为{4, 7, 2, 1, 5, 3, 6, 8},则重建出二叉树并输出它的头结点。
思路
- 前序遍历(前根遍历)中,遍历的第一个节点是根节点;中序遍历中,根节点在中间,且左边是左子树,右边是右子树。
- 采用递归的方法,构建左子树和右子树。
- 首先在前序遍历中提取根节点的值(1),在中序遍历中找到根节点的下标,此时将中序遍历分为{4,7,2}左子树,{5,3,6,8}右子树。
- 计算左子树个数,找到前序遍历中左右子树的分界线(递归中传递的参数,确定新的二叉树的范围)
代码
public class BinaryTreeNode{
private int data;
private BinaryTreeNode leftNode;
private BianryTreeNode rightNode;
public BinaryTreeNode(){
}
public BinaryTreeNode(int data){
this.data = data;
this.leftNode = null;
this.rightNode = null;
}
}
public class ReBuildBinaryTree{
/**
* pre[]前序遍历序列 startPre前序遍历起始位置 endPre前序遍历结尾
* in[] 中序遍历序列 stratIn中序遍历起始位置 endIn中序遍历末尾
**/
public BinaryTreeNode reBuild(int[] pre, int[] in) {
if(pre == null || in == null || in.length<=0) {
return null;
}
return reBuildCore(pre,0,pre.length-1,in,0,in.length-1);
}
public TreeNode reBuildCore(int[] pre, int startPre, int endPre, int[] in, int startIn, int endIn){
//当前根结点的值
int rootData = pre[startPre];
BinaryTreeNode root=new BinaryTreeNode(rootData);//创建根节点
root.leftNode = root.rightNode = null;
//只剩根节点一个元素时返回根节点
if(startPre==endPre)
{
if(startIn == endIn && pre[startPre] == in[startIn])
{
return root;
}
}
//找到根节点在中序序列中的位置
int rootIn = startIn;
while(rootIn <= endIn && in[rootIn] != rootData)
{
rootIn++;
}
//该根节点左子树的节点个数
int leftTreeLength = rootIn - startIn;
//得到前序序列中左子树的范围末尾
int preEnd = startPre + leftTreeLength;
//如果左子树有节点,创建左子树
if(leftTreeLength > 0
{
rootNode.left = reBuildCore(pre, startPre + 1, preEnd, in, startIn, rootIn - 1);
}
//右子树节点个数>0,则创建右子树
if(endPre - startPre - leftTreeLength > 0)
{
rootNode.right = reBuildCore(pre, preEnd + 1, endPre, in, rootIn + 1, endIn);
}
return root;
}
}