88.png

    1. /*
    2. 请设计一个算法,将给定的表达式树,转换成等价的中缀表达式并输出。
    3. 分析:
    4. 题目已然说明我们要采取中序遍历,进而输出该表达式,那么需要注意的点便是我们的括号在哪里加,其中根节点处和叶子结点
    5. 处不需要添加括号,其余情况在访问左子树前加左括号,访问右子树后添加右括号
    6. */
    7. struct BTree {
    8. char data;
    9. struct BTree *left, *right;
    10. };
    11. #define _CRT_SECURE_NO_WARNINGS
    12. #include <stdio.h>
    13. #include <stdlib.h>
    14. BTree *create(BTree *T) {//先序建立二叉树
    15. char data;
    16. printf("请输入当前节点值:data=");
    17. scanf("%c", &data);
    18. getchar();
    19. if (data != '#') {
    20. T = (BTree *)malloc(sizeof(BTree));
    21. T->data = data;
    22. T->left = NULL;
    23. T->right = NULL;
    24. T->left = create(T->left);
    25. T->right = create(T->right);
    26. }
    27. return T;
    28. }
    29. void putInExp(BTree *T,int deep) {
    30. if (T==NULL) {
    31. return;
    32. }
    33. if (!T->left&&!T->right) {//若为叶节点,直接输出操作数
    34. printf("%c",T->data);
    35. }
    36. else {
    37. if (deep > 1) printf("(");//非根节点,添加左括号
    38. putInExp(T->left,deep+1);
    39. printf("%c",T->data);
    40. putInExp(T->right, deep + 1);
    41. if (deep > 1) printf(")");
    42. }
    43. }
    44. int main() {
    45. struct BTree *T = (BTree *)malloc(sizeof(BTree));
    46. T = create(T);
    47. printf("中缀表达式为:");
    48. putInExp(T,1);
    49. return 0;
    50. }