杂七杂八——C#实现二叉树,外带中序遍历
发现用C#语法实现数据结构的时候,代码显得干净利落,嘻嘻。
- usingSystem;
- namespaceBinaryTree
- {
- //BinaryTree的结点类
- classNode
- {
- publicintData{get;set;}
- publicNodeLeftSubNode{get;set;}
- publicNodeRightSubNode{get;set;}
- //结点为自己追加子结点(与向左/向右追加结合,形成递归)
- publicvoidAppend(NodesubNode)
- {
- if(subNode.Data<=this.Data)
- {
- this.AppendLeft(subNode);
- }
- else
- {
- this.AppendRight(subNode);
- }
- }
- //向左追加
- publicvoidAppendLeft(NodesubNode)
- {
- if(this.LeftSubNode==null)
- {
- this.LeftSubNode=subNode;
- }
- else
- {
- this.LeftSubNode.Append(subNode);
- }
- }
- //向右追加
- publicvoidAppendRight(NodesubNode)
- {
- if(this.RightSubNode==null)
- {
- this.RightSubNode=subNode;
- }
- else
- {
- this.RightSubNode.Append(subNode);
- }
- }
- //结点显示自己的数据
- publicvoidShowData()
- {
- Console.WriteLine("Data={0}",this.Data);
- }
- }
- //BinaryTree类
- classTree
- {
- //根结点
- publicNodeRoot{get;set;}
- //以某结点为起点,插入结点
- publicvoidInsert(NodenewNode)
- {
- if(this.Root==null)
- {
- this.Root=newNode;
- }
- else
- {
- this.Root.Append(newNode);
- }
- }
- //重载,默认以根结点为起点插入
- publicvoidMidTravel()
- {
- this.MidTravel(this.Root);
- }
- //中序遍历(递归)
- publicvoidMidTravel(Nodenode)
- {
- if(node.LeftSubNode!=null)
- {
- this.MidTravel(node.LeftSubNode);
- }
- node.ShowData();
- if(node.RightSubNode!=null)
- {
- this.MidTravel(node.RightSubNode);
- }
- }
- }
- classProgram
- {
- staticvoidMain(string[]args)
- {
- Treetree=newTree();
- tree.Insert(newNode{Data=3});
- tree.Insert(newNode{Data=6});
- tree.Insert(newNode{Data=2});
- tree.Insert(newNode{Data=7});
- tree.Insert(newNode{Data=18});
- tree.MidTravel();
- }
- }
- }
- //水之真谛
- //http://blog.youkuaiyun.com/FantasiaX