`
lovnet
  • 浏览: 6704816 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
文章分类
社区版块
存档分类
最新评论

杂七杂八——C#实现二叉树,外带中序遍历

阅读更多

杂七杂八——C#实现二叉树,外带中序遍历

发现用C#语法实现数据结构的时候,代码显得干净利落,嘻嘻。

  1. usingSystem;
  2. namespaceBinaryTree
  3. {
  4. //BinaryTree的结点类
  5. classNode
  6. {
  7. publicintData{get;set;}
  8. publicNodeLeftSubNode{get;set;}
  9. publicNodeRightSubNode{get;set;}
  10. //结点为自己追加子结点(与向左/向右追加结合,形成递归)
  11. publicvoidAppend(NodesubNode)
  12. {
  13. if(subNode.Data<=this.Data)
  14. {
  15. this.AppendLeft(subNode);
  16. }
  17. else
  18. {
  19. this.AppendRight(subNode);
  20. }
  21. }
  22. //向左追加
  23. publicvoidAppendLeft(NodesubNode)
  24. {
  25. if(this.LeftSubNode==null)
  26. {
  27. this.LeftSubNode=subNode;
  28. }
  29. else
  30. {
  31. this.LeftSubNode.Append(subNode);
  32. }
  33. }
  34. //向右追加
  35. publicvoidAppendRight(NodesubNode)
  36. {
  37. if(this.RightSubNode==null)
  38. {
  39. this.RightSubNode=subNode;
  40. }
  41. else
  42. {
  43. this.RightSubNode.Append(subNode);
  44. }
  45. }
  46. //结点显示自己的数据
  47. publicvoidShowData()
  48. {
  49. Console.WriteLine("Data={0}",this.Data);
  50. }
  51. }
  52. //BinaryTree类
  53. classTree
  54. {
  55. //根结点
  56. publicNodeRoot{get;set;}
  57. //以某结点为起点,插入结点
  58. publicvoidInsert(NodenewNode)
  59. {
  60. if(this.Root==null)
  61. {
  62. this.Root=newNode;
  63. }
  64. else
  65. {
  66. this.Root.Append(newNode);
  67. }
  68. }
  69. //重载,默认以根结点为起点插入
  70. publicvoidMidTravel()
  71. {
  72. this.MidTravel(this.Root);
  73. }
  74. //中序遍历(递归)
  75. publicvoidMidTravel(Nodenode)
  76. {
  77. if(node.LeftSubNode!=null)
  78. {
  79. this.MidTravel(node.LeftSubNode);
  80. }
  81. node.ShowData();
  82. if(node.RightSubNode!=null)
  83. {
  84. this.MidTravel(node.RightSubNode);
  85. }
  86. }
  87. }
  88. classProgram
  89. {
  90. staticvoidMain(string[]args)
  91. {
  92. Treetree=newTree();
  93. tree.Insert(newNode{Data=3});
  94. tree.Insert(newNode{Data=6});
  95. tree.Insert(newNode{Data=2});
  96. tree.Insert(newNode{Data=7});
  97. tree.Insert(newNode{Data=18});
  98. tree.MidTravel();
  99. }
  100. }
  101. }
  102. //水之真谛
  103. //http://blog.csdn.net/FantasiaX
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics