二叉排序树(创建和插入)

以前看数据结构的时候都只是看,最近也没什么事情就重新看了一遍数据结构,感觉每一行代码写的都很经典,可惜都是C语言版的,所以我就想把它变成C#版的。

public class Node
    
{
        
public int key;
        
public string info;
        
public Node leftChild;
        
public Node rightChild;
    }

Note:用结构定义会报错,说:Node.leftChild”(属于类型“Node”)在结构布局中导致循环

public class BSTree
    
{
        
        
private static void InsertBSTree(ref Node root,Node node)
        
{
            Node parent 
= root;
            Node temp 
= new Node();
            
//查找位置
            while(parent != null)
            
{
                
if(parent.key == node.key)
                    
return;
                temp 
= parent;
                parent 
= (node.key < parent.key)?parent.leftChild:parent.rightChild;
            }

            
//在适当的位置插入
            if(root == null)
                root 
= node;
            
else
            
{
                
if(node.key < temp.key)
                    temp.leftChild 
= node;
                
else
                    temp.rightChild 
= node;
            }

        }

        
public static Node CreateBSTree(ArrayList list)
        
{
            Node root 
= null;
            
for(int i=0;i<list.Count;i++)
            
{
                Node n 
= (Node)list[i];
                InsertBSTree(
ref root,n);
            }

            
return root;
        }

    }
下面是测试代码:
public class TestSort
    
{
        
private static ArrayList array = new ArrayList();
        
public static void Main()
        
{
            Create();
            BSTree.CreateBSTree(array);
        }

        
public static void Create()
        
{
            System.Random r 
= new Random();
            
for(int i=0;i<10;i++)
            
{
                Node n 
= new Node();
                n.key 
= r.Next(100);
                n.info 
= "test";
                array.Add(n);
            }

        }

    }

posted on 2005-06-24 17:16  today  阅读(1611)  评论(1)    收藏  举报

导航

09夏旅游鞋代购专柜正品打折李宁/LINING男跑鞋休闲球鞋