手机版
你好,游客 登录 注册
背景:
阅读新闻

【递归】二叉树的先序建立及遍历

[日期:2012-12-08] 来源:Linux社区  作者:rainmote [字体: ]

数据间隔符为空格,例如:ABC--DE-G--F--- -代表空格

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<conio.h>
  4. typedefstruct tree
  5. {
  6. char ch;
  7. struct tree *lchild;
  8. struct tree *rchild;
  9. }TREE;
  10. void createTree(TREE **bt);
  11. void fristRoot(TREE **bt);
  12. void middleRoot(TREE **bt);
  13. void lastRoot(TREE **bt);
  14. void destroyTree(TREE **bt);
  15. int main()
  16. {
  17. TREE **bt;
  18. printf("Pleas input string:\n");
  19. bt = (TREE **)malloc(sizeof(TREE *));
  20. createTree(bt);
  21. printf("\n先序:\n");
  22. fristRoot(bt);
  23. printf("\n中序:\n");
  24. middleRoot(bt);
  25. printf("\n后序:\n");
  26. lastRoot(bt);
  27. printf("\n");
  28. destroyTree(bt);
  29. free(bt);
  30. return 0;
  31. }
  32. void createTree(TREE **bt)
  33. {
  34. char ch;
  35. ch = getche();
  36. if(ch == ' ')
  37. *bt = NULL;
  38. else
  39. {
  40. *bt = (TREE *)malloc(sizeof(TREE));
  41. (*bt)->ch = ch;
  42. createTree(&((*bt)->lchild));
  43. createTree(&((*bt)->rchild));
  44. }
  45. }
  46. void fristRoot(TREE **bt)
  47. {
  48. if( *bt != NULL)
  49. {
  50. printf("%c ", (*bt)->ch);
  51. fristRoot(&((*bt)->lchild));
  52. fristRoot(&((*bt)->rchild));
  53. }
  54. }
  55. void middleRoot(TREE **bt)
  56. {
  57. if( *bt != NULL)
  58. {
  59. middleRoot(&((*bt)->lchild));
  60. printf("%c ", (*bt)->ch);
  61. middleRoot(&((*bt)->rchild));
  62. }
  63. }
  64. void lastRoot(TREE **bt)
  65. {
  66. if( *bt != NULL)
  67. {
  68. lastRoot(&((*bt)->lchild));
  69. lastRoot(&((*bt)->rchild));
  70. printf("%c ", (*bt)->ch);
  71. }
  72. }
  73. void destroyTree(TREE **bt)
  74. {
  75. if( *bt != NULL)
  76. {
  77. destroyTree( &((*bt)->lchild) );
  78. destroyTree( &((*bt)->rchild) );
  79. free(*bt);
  80. }
  81. }
linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款