using System;
namespace 二叉树
{
#region 节点类
public class Node
{
private int x;
public Node left;
public Node right;
public Node(int n)
{
x = n;
}
public int X
{
get
{
return x;
}
set
{
x = value;
}
}
}
#endregion
#region 生成二叉树
public class BinaryTree
{
public Node head; //head是指向二叉树的根的变量
public Node point; //point是在生成二叉树时用来遍历节点的变量
public void CreateBinaryTree(Node node) //生成二叉树的方法
{
if(head == null)
{
this.head = node; //head指向二叉树的根
this.point = node; //point也指向根
return;
}
if(this.point.X < node.X)
if(this.point.right == null)
this.point.right = node;
else
{
point = point.right; //
this.CreateBinaryTree(node);
}
else
if(this.point.left == null)
this.point.left = node;
else
{
point = point.left;
this.CreateBinaryTree(node);
}
point = head;
}
#endregion
#region 遍历
public void DisplayBinaryTree(Node node)
{
if(node == null)
return;
DisplayBinaryTree(node.left);
Console.Write(" {0} ",node.X);
DisplayBinaryTree(node.right);
}
#endregion
}
#region 测试类
class Test
{
static void Main(string[] args)
{
Console.Write("请输入生成节点的个数:");
int number = Convert.ToInt32(Console.ReadLine());
int Value;
BinaryTree BT = new BinaryTree();
for(int i = 0; i < number; i++)
{
Console.Write("请输入第{0}个节点的数据:",i+1);
Value = Convert.ToInt32(Console.ReadLine());
Node node = new Node(Value);
BT.CreateBinaryTree(node);
}
BT.DisplayBinaryTree(BT.head);
}
}
#endregion
}
//老师写的二叉树
//using System;
//
//namespace ex060707_BinarySearchTree
//{
// public class Node
// {
// public int n;
// public Node Left;
// public Node Right;
// public Node(int a)
// {
// n = a;
// }
// public void InsertNode(Node node)
// {
// if(this.n < node.n)
// {
// if(this.Right == null)
// this.Right=node;
// else
// this.Right.InsertNode(node);
// }
// else
// {
// if(this.Left == null)
// this.Left=node;
// else
// this.Left.InsertNode(node);
//
// }
// }
// }
// public class BinarySearchTree
// {
// public Node Root;
// public void GenTree(Node node)
// {
// if(this.Root==null)
// {
// this.Root=node;
// return;
// }
// this.Root.InsertNode(node);
// }
// public void TranverseInOrder(Node node)
// {
// if(node == null) return;
// TranverseInOrder(node.Left);
// Console.WriteLine(node.n);
// TranverseInOrder(node.Right);
// }
// }
//
// class Test
// {
// static void Main()
// {
// BinarySearchTree bst = new BinarySearchTree();
//
// string s=Console.ReadLine();
// int a;
//
// while(s!="q")
// {
//
// while(true)
// {
// try
// {
// a=Convert.ToInt32(s);
// break;
// }
// catch(Exception e)
// {
// Console.WriteLine(e.Message +" pls input again:");
// s=Console.ReadLine();
// }
//
// }
// bst.GenTree(new Node(a));
// s=Console.ReadLine();
// }
//
// bst.TranverseInOrder(bst.Root);
//
//
// }
// }
//}