• c语言 数据结构 二叉树


    将下图中的二叉树用二叉链表表示:

    1. 用三种遍历算法遍历该二叉树,给出对应的输出结果;
    2. 写一个函数对二叉树搜索,若给出一个结点,根据其是否属于该树,输出true 或者false。 

    实验步骤

    1. 定义二叉树的结点类型及二叉树类型
    2. 递归方式建立二叉树(算法参见课本)
    3. 三种方式遍历二叉树(算法参见课本)
    1. #include
    2. #include
    3. #define ElemType char
    4. typedef int Status;
    5. typedef struct node //二叉树结点定义
    6. {
    7. ElemType data; //结点数据域
    8. struct node *lchild, *rchild; //左右孩子指针域
    9. } BTNode, *BiTree;
    10. BTNode *CreateBiTree()//按照前序遍历 序列建立二叉树
    11. {
    12. BTNode *root;
    13. char ch;
    14. scanf("%c", &ch);
    15. getchar();
    16. if (ch != '#') {
    17. root = (BTNode *) malloc(sizeof(BTNode));
    18. root->data = ch;
    19. printf("请输入%c的左子树:", ch);
    20. root->lchild = CreateBiTree();
    21. printf("请输入%c的右子树:", ch);
    22. root->rchild = CreateBiTree();
    23. } else
    24. root = NULL;
    25. return root;
    26. }
    27. void PreOrder(BTNode *r) {
    28. if (r != NULL) {
    29. printf("%6c", r->data);
    30. PreOrder(r->lchild);
    31. PreOrder(r->rchild);
    32. } else
    33. return;
    34. }
    35. void InOrder(BTNode *r) {
    36. if (r != NULL) {
    37. InOrder(r->lchild);
    38. printf("%6c", r->data);
    39. InOrder(r->rchild);
    40. } else
    41. return;
    42. }
    43. void PostOrder(BTNode *r) {
    44. if (r != NULL) {
    45. PostOrder(r->lchild);
    46. PostOrder(r->rchild);
    47. printf("%6c", r->data);
    48. } else
    49. return;
    50. }
    51. Status Search(BTNode *root, char ch) {
    52. int lable = 0;
    53. if (root != NULL) {
    54. if (ch == root->data) {
    55. lable = 1;
    56. } else {
    57. lable = Search(root->lchild, ch);
    58. if (lable == 0)
    59. lable = Search(root->rchild, ch);
    60. }
    61. }
    62. return lable;
    63. }
    64. int main() {
    65. BTNode *root;
    66. int lable;
    67. char ch;
    68. printf("请输入二叉树的根节点:");
    69. root = CreateBiTree();
    70. printf("\n");
    71. printf("前序遍历二叉树的遍历序列为:");
    72. PreOrder(root);
    73. printf("\n");
    74. printf("中序遍历二叉树的遍历序列为:");
    75. InOrder(root);
    76. printf("\n");
    77. printf("后序遍历二叉树的遍历序列为:");
    78. PostOrder(root);
    79. printf("\n");
    80. printf("---------------------------\n");
    81. printf("输入要查找的字符:");
    82. scanf("%c", &ch);
    83. getchar();
    84. lable = Search(root, ch);
    85. if (lable == 1)
    86. printf("找到%c,查找成功,值为:%s\n", ch, "true");
    87. else
    88. printf("未找到%c,查找失败,值为:%s\n", ch, "false");
    89. return 0;
    90. }

  • 相关阅读:
    ReentrantReadWriteLock(可重入读写锁)
    Codeforces Round #909 (Div. 3)
    ‘vue’不是内部或外部命令,也不是可运行的程序或批处理文件
    Java Opencv识别图片上的虫子
    如何使用命令提示符查询电脑相关序列号等信息的操作方法
    微信小程序开发流程
    【Vue】使用 Vue 实现基础的 CSS 过渡与动画效果
    善用 vscode 的多光标批量和模板等技巧来提效
    【JavaScript高级进阶】构造函数和原型,学会prototype
    ELK日志分析系统实战
  • 原文地址:https://blog.csdn.net/weixin_66397563/article/details/127831545