题目:
Given preorder and inorder traversal of a tree, construct the binary tree.
代码如下:
TreeNode *build(vector<int>&preorder,int m_beginp,int m_endp,vector<int> &inorder,intm_begini,int m_endi)
{
if(m_endp-m_beginp!=m_endi-m_begini)return NULL;
if(m_endp<m_beginp)return NULL;
TreeNode *root=new TreeNode(preorder[m_beginp]);
root->left=NULL;
root->right=NULL;
int i;
for(i=m_begini;i<=m_endi;i++)
{
if(preorder[m_beginp]==inorder[i])
{
break;
}
}
if(i>m_endi)return NULL;
if(i-m_begini>0)
root->left=build(preorder,m_beginp+1,m_beginp+i-m_begini,inorder,m_begini,i-1);
if(i<m_endi)
root->right=build(preorder,m_beginp+i-m_begini+1,m_endp,inorder,i+1,m_endi);
return root;
}
TreeNode *buildTree(vector<int> &preorder, vector<int>&inorder) {
return build(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
}