标签:
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 class Solution { 11 public: 12 struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) { 13 14 m_pre=pre; 15 m_in=in; 16 TreeNode* head; 17 head=reConstruct(0,pre.size()-1,0,in.size()-1); 18 return head; 19 } 20 21 struct TreeNode* reConstruct(int pre_L,int pre_R,int in_L,int in_R) 22 { 23 if(pre_L>pre_R||in_L>in_R) 24 return nullptr; 25 26 TreeNode *root = new TreeNode(m_pre[pre_L]); 27 int i=0; 28 while(m_pre[pre_L]!=m_in[i]) 29 i++; 30 31 root->left=reConstruct(pre_L+1,pre_L+i-in_L,in_L,i-1); 32 root->right=reConstruct(i+pre_L+1-in_L,pre_R,i+1,in_R); 33 34 return root; 35 } 36 37 private: 38 //代替全局变量 39 vector<int> m_pre; 40 vector<int> m_in; 41 42 };
标签:
原文地址:http://www.cnblogs.com/SeekHit/p/5818714.html