# Leetcode 105 Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.

Note: You may assume that duplicates do not exist in the tree.

```/**
* 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) {
if(preorder.empty()) return NULL;
TreeNode* root=new TreeNode(preorder[0]);
int pos;
for(int i=0;i<inorder.size();i++)
if(inorder[i]==preorder[0])
{
pos=i;
break;
}
vector<int> leftpre,leftin,rightpre,rightin;
for(int i=0;i<pos;i++)
{
leftpre.push_back(preorder[i+1]);
leftin.push_back(inorder[i]);
}
for(int i=pos+1;i<preorder.size();i++)
{
rightpre.push_back(preorder[i]);
rightin.push_back(inorder[i]);
}
root->left=buildTree(leftpre,leftin);
root->right=buildTree(rightpre,rightin);
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* dfs(vector<int>& preorder, int ps,int pe,vector<int>& inorder,int is,int ie)
{
if(ps>pe ) return NULL;
TreeNode* root=new TreeNode(preorder[ps]);
int pos;
for(int i=is;;i++)
if(inorder[i]==preorder[ps])
{
pos=i-is;
break;
}
root->left=dfs(preorder,ps+1,ps+pos,inorder,is,is+pos-1);
root->right=dfs(preorder,ps+pos+1,pe,inorder,is+pos+1,ie);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return dfs(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
}
};```

0 条评论