C#二叉树

View Code
  1 using System;

  2 using System.Collections.Generic;

  3 using System.Linq;

  4 using System.Text;

  5 

  6 namespace Sort

  7 {

  8     class Tree

  9     {

 10         static void Main(string[] args)

 11         {

 12             BinarySearchTree nums = new BinarySearchTree();

 13             nums.Insert(23);

 14             nums.Insert(45);

 15             nums.Insert(16);

 16             nums.Insert(37);

 17             nums.Insert(3);

 18             nums.Insert(99);

 19             nums.Insert(22);

 20             nums.Insert(23);

 21 

 22             Console.WriteLine("Inorder traversasl:");

 23             nums.InOrder(nums.root);

 24             Console.ReadKey();

 25 

 26         }

 27     }

 28 

 29     public class Node

 30     {

 31         public int Data;

 32 

 33         public Node Left = null;

 34         public Node Right = null;

 35 

 36         public void DisplayNode()

 37         {

 38             Console.Write(Data + " ");

 39         }

 40     }

 41 

 42     public class BinarySearchTree

 43     {

 44         public Node root;

 45         public BinarySearchTree()

 46         {

 47             root = null;

 48         }

 49         public void InOrder(Node theRoot)

 50         {

 51             if (!(theRoot == null))

 52             {

 53                 InOrder(theRoot.Left);

 54                 theRoot.DisplayNode();

 55                 InOrder(theRoot.Right);

 56             }

 57         }

 58 

 59 

 60         public void Insert(int i)

 61         {

 62             Node newNode = new Node();

 63             newNode.Data = i;

 64 

 65             if (root == null)

 66             {

 67                 root = newNode;

 68             }

 69             else

 70             {

 71                 Node current = root;

 72                 Node parent;

 73                 while (true)

 74                 {

 75                     parent = current;

 76                     if (i < current.Data)

 77                     {

 78                         current = current.Left;

 79 

 80                         if (current == null) //若左节点不为空则继续往下查找

 81                         {

 82                             parent.Left = newNode;

 83                             break;

 84                         }

 85                     }

 86                     else

 87                     {

 88                         current = current.Right;

 89 

 90                         if (current == null) //若右节点不为空则继续往下查找

 91                         {

 92                             parent.Right = newNode;

 93                             break;

 94                         }

 95                     }

 96                 } 

 97             }

 98         }

 99 

100     }

101 }

 

你可能感兴趣的:(二叉树)