题目:
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},
则重建二叉树并返回。
代码实现:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//递归实现
public class Solution {
public TreeNode reConstructBinaryTree(int []pre,int []in) {
TreeNode root=reConstructBinaryTree1(pre,0,pre.length-1,in,0,in.length-1);
return root;
}
//前序:{1,2,4,7,3,5,6,8}
//中序:{4,7,2,1,5,3,8,6}
public TreeNode reConstructBinaryTree1(int []pre,int startpre,int endpre,int []in,int startin,int endin)
{
if(startpre>endpre||startin>endin)
{
return null;
}
//根据前序遍历的特点可以找出根节点
TreeNode root=new TreeNode(pre[startpre]);
for(int i=startin;i<=endin;i++)
{
//在中序遍历中找到根节点
if(in[i]==pre[startpre])
{
//当startpre为根时,则左子树就从startpre+1,startpre+i-startin,
/*
如://前序:{1,2,4,7,3,5,6,8},中序:{4,7,2,1,5,3,8,6}
左子树第一次起始位置下标:中序:1~3,后序:0~2
右子树第一次起始位置下标:中序:4~7,后序:4~7
然后依次递归实现。
*/
root.left=reConstructBinaryTree1(pre,startpre+1, startpre+i-startin,in,startin,i-1);
root.right=reConstructBinaryTree1(pre,i+1+startpre-startin,endpre,in,i+1,endin);
}
}
return root;
}
}