题目
题目来源 : LeetCode
实现
struct TreeNode* _buildTree(int* inorder, int* postorder, int* curindex, int begin, int end){
//创建根节点
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = postorder[*curindex];
//在中序遍历中寻找根节点的位置
int rootindex = end;
for(;rootindex >= 0; --rootindex){
if(inorder[rootindex] == root->val){
break;
}
}
//创建右子树
if(end > rootindex){
--(*curindex);
root->right = _buildTree(inorder, postorder, curindex, rootindex + 1, end);
}else{
root->right = NULL;
}
//创建左子树
if(begin < rootindex){
--(*curindex);
root->left = _buildTree(inorder, postorder, curindex, begin, rootindex - 1);
}else{
root->left = NULL;
}
return root;
}
struct TreeNode* buildTree(int* inorder, int inorderSize, int* postorder, int postorderSize){
//从最后开始
int curindex = inorderSize - 1;
if(inorderSize == 0 || postorderSize == 0){
return NULL;
}
return _buildTree(inorder, postorder, &curindex, 0, inorderSize - 1);
}