歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 【遞歸】二叉樹的先序建立及遍歷

【遞歸】二叉樹的先序建立及遍歷

日期:2017/3/1 10:05:59   编辑:Linux編程

數據間隔符為空格,例如: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. }
Copyright © Linux教程網 All Rights Reserved