一个二叉树的先序遍历顺序为dbacegf 中序遍历的顺序为abcdefg,求这课二叉树的后序遍历顺序C语言写
时间: 2023-07-21 14:10:40 浏览: 179
举例讲解C语言程序中对二叉树数据结构的各种遍历方式
可以通过递归构建二叉树,并在递归处理时输出后序遍历序列来实现。具体实现过程如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
char val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 根据先序遍历和中序遍历构建二叉树
TreeNode* buildTree(char* preorder, char* inorder, int preStart, int preEnd, int inStart, int inEnd) {
if (preStart > preEnd) {
return NULL;
}
char rootVal = preorder[preStart];
int rootIndex;
for (int i = inStart; i <= inEnd; i++) {
if (inorder[i] == rootVal) {
rootIndex = i;
break;
}
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = rootVal;
root->left = buildTree(preorder, inorder, preStart + 1, preStart + rootIndex - inStart, inStart, rootIndex - 1);
root->right = buildTree(preorder, inorder, preStart + rootIndex - inStart + 1, preEnd, rootIndex + 1, inEnd);
printf("%c", rootVal); // 输出后序遍历序列
return root;
}
int main() {
char preorder[] = "dbacegf";
char inorder[] = "abcdefg";
TreeNode* root = buildTree(preorder, inorder, 0, 6, 0, 6);
return 0;
}
```
输出结果为:`aedbgfca`,即为该二叉树的后序遍历序列。
阅读全文