/**
* 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) {
return create(inorder,postorder,0,inorder.size()-1,0,postorder.size()-1);
}
TreeNode* create(vector<int>& inorder, vector<int>& postorder,int is,int ie,int ps,int pe){
if(ps>pe)
return NULL;
int index;
for(int i=is;i<=ie;i++){
if(inorder[i]==postorder[pe]){
index=i;
break;
}
}
TreeNode* node=new TreeNode(postorder[pe]);
node->left=create(inorder,postorder,is,index-1,ps,ps+index-is-1);
node->right=create(inorder,postorder,index+1,ie,index-ie+pe,pe-1);
return node;
}
};
106. Construct Binary Tree from Inorder and Postorder Traversal
最新推荐文章于 2020-12-18 21:27:39 发布