杂七杂八——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.youkuaiyun.com/FantasiaX
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值