根据中序遍历和后序遍历树构造二叉树
样例
样例 1:
输入:[],[]
输出:{}
解释:
二叉树为空
样例 2:
输入:[1,2,3],[1,3,2]
输出:{2,1,3}
解释:
二叉树如下
2
/ \
1 3
注意事项
你可以假设树中不存在相同数值的节点
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param inorder: A list of integers that inorder traversal of a tree
* @param postorder: A list of integers that postorder traversal of a tree
* @return: Root of a tree
*/
TreeNode * buildTree(vector<int> &inorder, vector<int> &postorder)
{
// write your code here
int n = inorder.size();
TreeNode* ret =NULL;
int *in = new int[n];
if (!inorder.empty())
{
memcpy(in, &inorder[0], n*sizeof(int));
}
int *post = new int[n];
if (!postorder.empty())
{
memcpy(post, &postorder[0], n*sizeof(int));
}
ret = CreatBT2(post, in, n);
return ret;
}
TreeNode* CreatBT2(int* post, int* in, int n)
{
TreeNode* b;
int *p;
int r; //根结点的值
int k ;
if(n <= 0)
{
return NULL;
}
r = *(post+n-1);
b = new TreeNode(r);
for(p=in; p<in+n; p++)
{
if(*p == r)
break;
}
k = p-in;
b->left = CreatBT2(post, in, k);
b->right = CreatBT2(post+k, p+1, n-k-1);
return b;
}
};