返回与给定的前序和后序遍历匹配的任何二叉树。
pre 和 post 遍历中的值是不同的正整数。
1 <= pre.length == post.length <= 30
pre[]和 post[] 都是 1, 2, …, pre.length 的排列
每个输入保证至少有一个答案。如果有多个答案,可以返回其中一个。
样例
样例 1:
输入:pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
输出:[1,2,3,4,5,6,7]
解释:
1
/
2 3
/ \ /
4 5 6 7
样例 2:
输入:pre = [1,2,3,4], post = [3,2,4,1]
输出:[1,2,4,3]
解释:
1
/
2 4
/
3
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
/*
算法:
1、将pre的第一个元素作为root;
2、将pre中剩下的元素分为左子树元素和右子树元素
3、递归创建左子树和右子树
区分左子树和右子树原则:pre的第一个元素和post的最后一个元素相同
*/
class Solution {
public:
TreeNode * constructFromPrePost(vector<int> pre, vector<int> post) {
// write your code here
if (pre.empty() || post.empty())
return