# leetcode-前序后序得到二叉树

### 示例

前序遍历 preorder = [3,9,20,15,7]



    3
/ \
9  20
/  \
15   7


### 代码(c++)

class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(!preorder.size()) return NULL;
TreeNode* root=new TreeNode(preorder[0]);
int index=0;
stack<TreeNode*> data;
data.push(root);
for(int i=1;i<preorder.size();i++){
int value=preorder[i];
TreeNode* node=data.top();
if(node->val!=inorder[index]){
node->left=new TreeNode(value);
data.push( node->left);
}else{
while(!data.empty()&&data.top()->val==inorder[index]){
node=data.top();
data.pop();
index++;
}
node->right=new TreeNode(value);
data.push(node->right);
}

}
return root;
}


### 附录：差不多的解答方式，但是代码有误

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
map<int,int> local;
int n=preorder.size();
map<int,pair<int,int>> result;
stack<int> flag;
flag.push(preorder[n-1]);
for(int i=0;i<n;i++){
local[inorder[i]]=i;
}
for(int i=0;i<n;i++){
if(flag.empty()) break;
int data=local[flag.top()];
int nowdata=local[preorder[i]];
if(data>nowdata){
flag.push(preorder[i]);
//是top的左子树
result[flag.top()].first=preorder[i];
}else{
int lastdata=flag.top();
while(data<nowdata){
lastdata=flag.top();
flag.pop();
if(flag.empty()) break;
data=local[flag.top()];
}
result[lastdata].second=preorder[i];
}
}
resultNum=result;
return is(preorder[0]);
}
TreeNode* is(int data){
TreeNode* treedata=new TreeNode;
treedata->val=data;
if(resultNum[data].first==0){
return treedata;
}else{
treedata->left=is(resultNum[data].first);
treedata->right=is(resultNum[data].second);
return treedata;
}
}
private:
map<int,pair<int,int>> resultNum;
};


06-15 1295

04-13 363

08-06 189

01-15 49

08-20 2302

03-21 563

06-24 759

09-13 336

09-01 173

03-29 213

05-13 53

08-21 79

04-21 87

05-14 39

08-23 110

09-02 78

09-01 326

08-19 2916

12-06 83

03-19 83万+

#### 大学四年自学走来，这些私藏的实用工具/学习网站我贡献出来了

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试