# [leetcode]106. Construct Binary Tree from Inorder and Postorder Traversal

/**
* 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>& inorder, vector<int>& postorder)
{
int len=inorder.size();
if(len==0)
return {};
else
return build(inorder,postorder,0,len-1,0,len-1);
}
TreeNode* build(vector<int>& inorder, vector<int>& postorder,int inL,int inR, int postL,int postR)
{
if(inR<inL||postR<postL)
return {};

TreeNode* root=new TreeNode(postorder[postR]);

if(inL==inR||postL==postR)
return root;

int mid;
for(int i=inL;i<=inR;i++)
{
if(inorder[i]==postorder[postR])
{
mid=i;
break;
}
}

root->left=build(inorder,postorder,inL,mid-1, postL,postL+mid-inL-1);
root->right=build(inorder,postorder,mid+1,inR,postL+mid-inL,postR-1);

return root;
}
};

• 本文已收录于以下专栏：

举报原因： 您举报文章：[leetcode]106. Construct Binary Tree from Inorder and Postorder Traversal 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)