题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
根据前序遍历序列找到子树根节点,并在中序遍历序列中找到该点,以分割左右子树的序列
1 public class Solution {//树 my 2 public TreeNode reConstructBinaryTree(int [] pre,int [] in) { 3 return reConBTreeIndex(pre,0,pre.length-1,in,0,in.length-1); 4 } 5 private TreeNode reConBTreeIndex(int[] pre,int preLeft,int preRight,int[] in,int inLeft,int inRight){ 7 if(preRight<preLeft||inLeft>inRight){ 8 return null; 9 } 10 else{ 11 //System.out.println(pre[preLeft]+"--"+pre[preRight]+" "+in[inLeft]+"--"+in[inRight]); 12 TreeNode node = new TreeNode(pre[preLeft]); 13 for (int i = inLeft; i <= inRight; i++) { 14 if(in[i]==pre[preLeft]){ 15 node.left = reConBTreeIndex(pre,preLeft+1,i-inLeft+preLeft,in,inLeft,i-1); 16 node.right = reConBTreeIndex(pre,preRight-inRight+i+1,preRight,in,i+1,inRight); 17 } 18 } 19 return node; 20 } 21 } 22 }