1.从中序和后序遍历序列构造二叉树
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return buildTree2(inorder,postorder,0,postorder.size()-1,0,inorder.size()-1);
}
TreeNode* buildTree2(vector<int>& inorder, vector<int>& postorder,int ins,int inend,int pos,int poend){
if(pos>poend) return NULL;
TreeNode* treeNode=new TreeNode(postorder[poend]);
int im = ins ;
while (im<inend&&inorder[im]!=postorder[poend]){
im++;
}
treeNode->left = buildTree2(inorder,postorder,ins,im-1,pos,pos+im-ins-1);
treeNode->right = buildTree2(inorder,postorder,im+1,inend,poend-inend+im,poend-1);
return treeNode;
}
};
2.从中序和前序遍历序列构造二叉树
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return buildTree2(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1);
}
TreeNode* buildTree2(vector<int>& preorder, vector<int>& inorder,int prs,int prend,int ins,int inend){
if(prs>prend) return NULL;
TreeNode* treeNode=new TreeNode(preorder[prs]);
int im = ins ;
while (im<inend&&inorder[im]!=preorder[prs]){
im++;
}
treeNode->left = buildTree2(preorder,inorder,prs+1,prs+im-ins,ins,im-1);
treeNode->right = buildTree2(preorder,inorder,prs+im-ins+1,prend,im+1,inend);
return treeNode;
}
};