c#二叉排序树实现

主要是二叉排序树的构建和显示

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));


    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值