标签:
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 11 struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) { 12 if(pre.size()==0||in.size()==0) 13 { 14 return NULL; 15 } 16 if(pre.size()==1) 17 { 18 return new TreeNode(pre.front()); 19 } 20 if(in.size()==1) 21 { 22 return new TreeNode(in.front()); 23 } 24 int node_Val=pre.front();//用来存根节点的值 25 auto node_in=find(in.begin(),in.end(),node_Val);//根节点在in的位置 26 27 //左子树区间 28 vector<int> left_in_Block(in.begin(),node_in); 29 int move=node_in-in.begin(); 30 vector<int> left_pre_Block(++pre.begin(),pre.begin()+move+1); 31 32 //右子树区间 33 vector<int> right_in_Block(++node_in,in.end()); 34 vector<int> right_pre_Block(pre.begin()+move+1,pre.end()); 35 36 TreeNode *node=new TreeNode(node_Val);//根节点 37 node->left=reConstructBinaryTree(left_pre_Block,left_in_Block); 38 node->right=reConstructBinaryTree(right_pre_Block,right_in_Block); 39 return node; 40 }
标签:
原文地址:http://www.cnblogs.com/firstcxj/p/4822271.html