题目描述
返回与给定的前序和后序遍历匹配的任何二叉树。
pre 和 post 遍历中的值是不同的正整数。
示例:
输入:pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
输出:[1,2,3,4,5,6,7]
提示:
1 <= pre.length == post.length <= 30
pre[] 和 post[] 都是 1, 2, …, pre.length 的排列
每个输入保证至少有一个答案。如果有多个答案,可以返回其中一个。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* constructFromPrePost(int* pre, int preSize, int* post, int postSize) {
if(preSize==0)
return NULL;
struct TreeNode* root= (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val=pre[0];
if(preSize==1) {
root->left=NULL;
root->right=NULL;
}
else{
int i=0;
for(;post[i]!=pre[1];i++);
root->left=constructFromPrePost(pre+1,i+1,post,i+1);
root->right=constructFromPrePost(pre+i+2, postSize-i-2, post+i+1,postSize-i-2);
}
return root;
}