### 根據兩種不同遍歷結果重構二叉樹

leetcode原題：題目1 題目2

``````/** * 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 {
TreeNode* dfs(int post, int instart, int inend,vector<int>& inorder, vector<int>& postorder)
{
if(post<0||instart>inend)
return NULL;
TreeNode* root=new TreeNode(postorder[post]);
int index=0;
for(int i=instart;i<=inend;i++)
if(inorder[i]==postorder[post])
{
index=i;
break;
}
TreeNode* left=dfs(post-(inend-index)-1,instart,index-1,inorder,postorder);
TreeNode* right=dfs(post-1,index+1,inend,inorder,postorder);
root->left=left;
root->right=right;
return root;
}
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
int n=postorder.size();
return dfs(n-1,0,n-1,inorder,postorder);
}
};``````

``````/** * 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 {
TreeNode * dfs(int preStart, int inStart, int inEnd, vector<int>& preorder, vector<int>& inorder)
{
if(preStart>preorder.size()-1||inStart>inEnd)
return NULL;
TreeNode* root=new TreeNode(preorder[preStart]);
int index=0;
for(int i=inStart;i<=inEnd;i++)
if(inorder[i]==preorder[preStart])
{ index=i;break;}
TreeNode* left=dfs(preStart+1,inStart,index-1,preorder,inorder);
TreeNode* right=dfs(preStart+index-inStart+1,index+1,inEnd,preorder,inorder);
root->left=left;
root->right=right;
return root;
}
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return dfs(0,0,inorder.size()-1,preorder,inorder);
}
};``````