[分享]书中一段关于"二叉树"的代码
分享书中的一段代码,关于二叉树数据结构的,感觉内的嵌套特精典,所以分享给大家using System;
using System.Collections.Generic;
using System.Text;
namespace BinaryTree
{
public class Tree<T> where T : IComparable<T>
{
private T data;
private Tree<T> left;
private Tree<T> right;
public Tree(T nodeValue)
{
this.data = nodeValue;
this.left = null;
this.right = null;
}
public T NodeData
{
get { return this.data; }
set { this.data = value; }
}
public Tree<T> LeftTree
{
get { return this.left; }
set { this.left = value; }
}
public Tree<T> RightTree
{
get { return this.right; }
set { this.right = value; }
}
public void Insert(T newItem)
{
T currentNodeValue = this.NodeData;
if (currentNodeValue.CompareTo(newItem) > 0)
{
if (this.LeftTree == null)
{
this.LeftTree = new Tree<T>(newItem);
}
else
{
this.LeftTree.Insert(newItem);
}
}
else
{
if (this.RightTree == null)
{
this.RightTree = new Tree<T>(newItem);
}
else
{
this.RightTree.Insert(newItem);
}
}
}
public void WalkTree()
{
if (this.LeftTree != null)
{
this.LeftTree.WalkTree();
}
Console.WriteLine(this.NodeData.ToString());
if (this.RightTree != null)
{
this.RightTree.WalkTree();
}
}
}
}