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