利用二叉樹的排序演算法c#實現
阿新 • • 發佈:2019-01-22
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();
}
}
}