class Solution {
public:
void _Convert(TreeNode* cur,TreeNode*& prev)
{
if(cur==nullptr)
return;
_Convert(cur->left,prev);
cur->left=prev;
if(prev)
{
prev->right=cur;
}
prev=cur;
_Convert(cur->right,prev);
}
TreeNode* Convert(TreeNode* pRootOfTree) {
TreeNode* cur=pRootOfTree,*prev=nullptr;
_Convert(cur,prev);
TreeNode* root=pRootOfTree;
while(root && root->left)
{
root=root->left;
}
return root;
}
};
class Solution {
public:
TreeNode* _buildTree(vector<int>& preorder, vector<int>& inorder,int& i,int begin,int end)
{
if(begin>end)
return nullptr;
int rooti=begin;
while(rooti<=end)
{
if(preorder[i]==inorder[rooti])
break;
rooti++;
}
TreeNode* root=new TreeNode(preorder[i++]);
root->left=_buildTree(preorder,inorder,i,begin,rooti-1);
root->right=_buildTree(preorder,inorder,i,rooti+1,end);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int i=0;
TreeNode* root=_buildTree(preorder,inorder,i,0,inorder.size()-1);
return root;
}
};
class Solution {
public:
TreeNode* _buildTree(vector<int>& inorder, vector<int>& postorder,
int& i,int begin,int end)
{
if(begin>end)
return nullptr;
int rooti=begin;
while(begin<=end)
{
if(postorder[i]==inorder[rooti])
break;
rooti++;
}
TreeNode* root=new TreeNode(postorder[i--]);
root->right=_buildTree(inorder,postorder,i,rooti+1,end);
root->left=_buildTree(inorder,postorder,i,begin,rooti-1);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
int i=postorder.size()-1;
TreeNode* root=_buildTree(inorder,postorder,i,0,inorder.size()-1);
return root;
}
};