利用二叉树的排序算法c#实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 利用二叉树的排序算法
{
    public class Tree
    {
        public int data;//数据
        public Tree left;//左子树
        public Tree right;//右子树
        public static void Insert(Tree tree, int num)
        {
            if (tree.data <= num)
            {
                if (tree.right != null)
                {
                    Insert(tree.right, num);
                }
                else
                {
                    Tree right = new Tree { data = num };
                    tree.right = right;
                }
            }
            else
            {
                if (tree.left != null)
                {
                    Insert(tree.left, num);
                }
                else
                {
                    Tree left = new Tree { data = num };
                    tree.left = left;
                }
            }
        }
        //树的遍历
        public static void Travel(Tree tree)
        {
            if (tree.left != null)
                Travel(tree.left);
            Console.Write(tree.data + "   ");
            if (tree.right != null)
                Travel(tree.right);
        }
    }
    class Program
    {
        public static Tree tree;


        public static void sort(int[] a)
        {
            tree = new Tree { data = a[0] };
            for (int i = 1; i < a.Length; i++)
            {
                Tree.Insert(tree, a[i]);
            }
        }
        static void Main(string[] args)
        {
            int[] a = { 3, 5, 3, 6, 4, 7, 5, 7, 4, 1, 15, 8, 10, 9 };
            Console.WriteLine("原始数据");
            foreach (var item in a)
            {
                Console.Write(item + "   ");
            }
            Console.WriteLine();
            Console.WriteLine("排序后数据");
            sort(a);
            Tree.Travel(tree);
            Console.ReadLine();
        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值