由于先序和后序只是反映了结点之间的父子关系,没有反映出左右关系。因此构造的树是不唯一的。
/**
* 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* construct(vector<int>& pre, int startPre, int endPre, vector<int>& post, int startPost, int endPost) {
if(startPre>endPre || startPost>endPost) return NULL;
//先序序列的第一个就是当前子树的根节点
TreeNode* root = new TreeNode(pre[startPre]);
//如果序列只剩下一个节点,则直接返回
if(startPre==endPre) return root;
//先序序列的第二个就是当前子树的左子节点
//由于左子树的后序遍历的最后一个节点就是左子树的根节点,因此以`pre[startPre+1]`为界限就可以区分左右子树
int nextval=pre[startPre+1];
int endLeftPost;
for(int i=startPost;i<endPost;++i){
if(post[i]==nextval){
endLeftPost=i;
break;
}
}
int lenLeft = endLeftPost-startPost;
//如果没有右子树
if(endLeftPost==(endPost-1))
root->left=construct(pre,startPre+1,endPre,post,startPost,endPost-1);
else{
root->left=construct(pre,startPre+1,startPre+lenLeft+1,post,startPost,endLeftPost);
root->right=construct(pre,startPre+lenLeft+2,endPre,post,endLeftPost+1,endPost-1);
}
return root;
}
TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
int lenPre = pre.size();
int lenPost = post.size();
return construct(pre,0,lenPre-1,post,0,lenPost-1);
}
};