(7)树的建立和遍历.cpp
上传用户:wxj1219
上传日期:2013-01-31
资源大小:6k
文件大小:1k
源码类别:

数据结构

开发平台:

C/C++

  1. #include<conio.h>
  2. #include<iostream.h>
  3. struct Node
  4. {
  5. char Data;
  6. Node *Left,*Right;
  7. };
  8. Node *Root=NULL;
  9. char LeafCount=0;
  10. void Create(Node *&Tree)
  11. {
  12. char Char;
  13. Char=getch();
  14. cout<<Char;
  15. if(Char==' ')
  16. Tree=NULL;
  17. else
  18. {
  19. Tree=new Node;
  20. if(Root==NULL)
  21. Root=Tree;
  22. Tree->Data=Char;
  23. Create(Tree->Left);
  24. Create(Tree->Right);
  25. if((Tree->Left==NULL)&&(Tree->Right==NULL))
  26. LeafCount++;
  27. }
  28. }
  29. void PreOrder(Node *Tree)
  30. {
  31. if(Tree==NULL)
  32. return;
  33. cout<<Tree->Data;
  34. PreOrder(Tree->Left);
  35. PreOrder(Tree->Right);
  36. }
  37. void PostOrder(Node *Tree)
  38. {
  39. if(Tree==NULL)
  40. return;
  41. PostOrder(Tree->Left);
  42. PostOrder(Tree->Right);
  43. cout<<Tree->Data;
  44. }
  45. void InOrder(Node *Tree)
  46. {
  47. if(Tree==NULL)
  48. return;
  49. InOrder(Tree->Left);
  50. cout<<Tree->Data;
  51. InOrder(Tree->Right);
  52. }
  53. void Exchange(Node *Tree)
  54. {
  55. Node *TempNode;
  56. if(Tree==NULL)
  57. return;
  58. Exchange(Tree->Left);
  59. Exchange(Tree->Right);
  60. TempNode=Tree->Left;
  61. Tree->Left=Tree->Right;
  62. Tree->Right=TempNode;
  63. }
  64. void main()
  65. {
  66. clrscr();
  67. Create(Root);
  68. cout<<endl;
  69. PreOrder(Root);
  70. cout<<endl;
  71. PostOrder(Root);
  72. cout<<endl;
  73. InOrder(Root);
  74. cout<<endl;
  75. Exchange(Root);
  76. PreOrder(Root);
  77. cout<<endl;
  78. cout<<(int)LeafCount;
  79. }