给出后序遍历构建二叉树c++
时间: 2023-04-09 15:04:39 浏览: 93
建立遍历二叉树C++
可以使用递归的方式来实现,具体代码如下:
struct TreeNode* buildTree(int* inorder, int inorderSize, int* postorder, int postorderSize){
if (inorderSize == 0 || postorderSize == 0) {
return NULL;
}
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = postorder[postorderSize - 1];
int i;
for (i = 0; i < inorderSize; i++) {
if (inorder[i] == root->val) {
break;
}
}
root->left = buildTree(inorder, i, postorder, i);
root->right = buildTree(inorder + i + 1, inorderSize - i - 1, postorder + i, postorderSize - i - 1);
return root;
}
阅读全文