主要是二叉排序树的构建和显示
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Text;
public class Node
{
public int data;
public Node left;
public Node right;
public void print()
{
Console.WriteLine(data); //打印数据
}
}
public class BinarySearchTree
{
public Node Root;
public BinarySearchTree()
{
Root = null;
}
public void Insert(int i)
{
Node newnode=new Node();
newnode.data = i; //赋予新的值
if (Root == null)
{
Root = newnode; //将这个节点作为根节点
return;
}
Node current=Root;
while (true)
{
if (i < current.data)
{//如果这个节点比当前节点小
if(current.left!=null)
current = current.left;
else
{
current.left = newnode;
break;
}
}
else
{
if (current.right != null)
current = current.right;
else
{
current.right = newnode;
break;
}
}
}
}
//中序遍历二叉树
public void show(Node theroot)
{
if (theroot != null)
{
show(theroot.left);
theroot.print();
show(theroot.right);
}
}
//查找最大值
public int showMin()
{
Node current = Root;
while (current.left!=null)
{
current = current.left;
}
return current.data;
}
public int showMax()
{
Node current = Root;
while (current.right != null)
current = current.right;
return current.data;
}
public bool Find(int i)
{//查找某一节点是否在树中
Node current = Root;
while (current!=null)
{
if (i < current.data)
{
current = current.left;
}
else if (i > current.data)
{
current = current.right;
}
else
{
return true;
}
}
return false;
}
}
public class Test
{
public static void Main()
{
BinarySearchTree node=new BinarySearchTree();
node.Insert(5);
node.Insert(4);
node.Insert(6);
node.Insert(3);
node.Insert(1);
node.show(node.Root);
Console.WriteLine("最大值:"+node.showMin());
Console.WriteLine("最小值:"+node.showMax());
Console.WriteLine("这个节点:"+node.Find(4));
}
}