输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
思路: 由于前序遍历首先遍历的就是根节点,所以创建的二叉树的根节点确定。然后需要创建二叉树的左子树和右子树,这里采用递归的思想,将前序遍历和中序遍历各分成左子树和右子树
public class Solution { public TreeNode reConstructBinaryTree(int [] pre,int [] in) { return createTree(pre,in,0,pre.length-1,0,in.length-1); } public TreeNode createTree(int[] pre,int[] in,int l1,int r1,int l2,int r2){ if(l1>r1) return null; TreeNode root=new TreeNode(pre[l1]); //创建根节点 int mid=l2; while(in[mid]!=pre[l1]){ mid++; } int length=mid-l2; //找到左子树的个数 root.left=createTree(pre,in,l1+1,l1+length,l2,l2+length-1); //创建左子树 root.right=createTree(pre,in,l1+length+1,r1,mid+1,r2); //创建右子树 return root; } }剑指offer编程题