/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ //重建二叉树,最重要是找到根节点,然后找其左子树和右子树 import java.util.Map; import java.util.HashMap; public class Solution { public TreeNode reConstructBinaryTree(int [] pre,int [] in) { if(pre==null||in ==null) return null; Map map=new HashMap();//利用了map的get方法可以找到根节点的index,然后再进行递归 for(int i=0;i map) { if(pi>pend) return null; TreeNode head = new TreeNode(pre[pi]); int index=map.get(pre[pi]); head.left=preIn(pre,pi+1,index+pi-ni,in,ni,index-1,map); head.right=preIn(pre,index+pi-ni+1,pend,in,index+1,nend,map); return head; } } /* 先序遍历第一个位置肯定是根节点node,    中序遍历的根节点位置在中间p,在p左边的肯定是node的左子树的中序数组,p右边的肯定是node的右子树的中序数组    另一方面,先序遍历的第二个位置到p,也是node左子树的先序子数组,剩下p右边的就是node的右子树的先序子数组   把四个数组找出来,分左右递归调用即可 */ class Solution {       public:           struct TreeNode* reConstructBinaryTree(vector pre,vector in) {               int inlen=in.size();               if(inlen==0)                   return NULL;               vector left_pre,right_pre,left_in,right_in;               //创建根节点,根节点肯定是前序遍历的第一个数               TreeNode* head=new TreeNode(pre[0]);               //找到中序遍历根节点所在位置,存放于变量gen中               int gen=0;               for(int i=0;ileft=reConstructBinaryTree(left_pre,left_in);              head->right=reConstructBinaryTree(right_pre,right_in);              return head;           }       };   */