本文共 1656 字,大约阅读时间需要 5 分钟。
发现用C#语法实现数据结构的时候,代码显得干净利落,嘻嘻。
- using System;
- namespace BinaryTree
- {
-
- class Node
- {
- public int Data { get; set; }
- public Node LeftSubNode { get; set; }
- public Node RightSubNode { get; set; }
-
- public void Append(Node subNode)
- {
- if (subNode.Data <= this.Data)
- {
- this.AppendLeft(subNode);
- }
- else
- {
- this.AppendRight(subNode);
- }
- }
-
- public void AppendLeft(Node subNode)
- {
- if (this.LeftSubNode == null)
- {
- this.LeftSubNode = subNode;
- }
- else
- {
- this.LeftSubNode.Append(subNode);
- }
- }
-
- public void AppendRight(Node subNode)
- {
- if (this.RightSubNode == null)
- {
- this.RightSubNode = subNode;
- }
- else
- {
- this.RightSubNode.Append(subNode);
- }
- }
-
- public void ShowData()
- {
- Console.WriteLine("Data={0}", this.Data);
- }
- }
-
- class Tree
- {
-
- public Node Root { get; set; }
-
- public void Insert(Node newNode)
- {
- if (this.Root == null)
- {
- this.Root = newNode;
- }
- else
- {
- this.Root.Append(newNode);
- }
- }
-
- public void MidTravel()
- {
- this.MidTravel(this.Root);
- }
-
-
- public void MidTravel(Node node)
- {
- if (node.LeftSubNode != null)
- {
- this.MidTravel(node.LeftSubNode);
- }
- node.ShowData();
- if (node.RightSubNode != null)
- {
- this.MidTravel(node.RightSubNode);
- }
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Tree tree = new Tree();
-
- tree.Insert(new Node { Data = 3 });
- tree.Insert(new Node { Data = 6 });
- tree.Insert(new Node { Data = 2 });
- tree.Insert(new Node { Data = 7 });
- tree.Insert(new Node { Data = 18 });
-
- tree.MidTravel();
- }
- }
- }
-
-
本文转自 水之真谛 51CTO博客,原文链接:http://blog.51cto.com/liutiemeng/95289,如需转载请自行联系原作者