代码改变世界

二叉排序树

2011-01-21 14:53  Clingingboy  阅读(440)  评论(0编辑  收藏  举报

 

1.

public class Node
{
    public Node(int key)
    {
        Value = key;
    }

    public int Value { get; set; }

    public Node Left { get; set; }

    public Node Right { get; set; }

    public void Display()
    {
        Node current = this;
        if (current != null)
        {
            Console.Write("parent: "+this.Value);
            if (current.Left != null)
                Console.Write(" left: "+current.Left.Value);
            if (current.Right != null)
                Console.Write(" right: " + current.Right.Value);
            Console.WriteLine();
            if (current.Left != null)
                current.Left.Display();
            if (current.Right != null)
                current.Right.Display();
        }
    }
}

public class BSTree
{


    private Node _root;

    public void Display()
    {
        Node current = _root;
        if(current!=null)
        {
           _root.Display();
        }
    }

    public Node Find(int key)
    {
        Node current = _root;
        while (current != null && current.Value != key)
        {
            current = key < current.Value ? current.Left : current.Right;
        }
        return current;
    }

    public void Insert(int key)
    {
        var newNode = new Node(key);
        if (_root == null)
        {
            _root = newNode;
            return;
        }
        Node current = _root;
        Node parent;
        while (true)
        {
            parent = current;
            if (key < current.Value)
            {
                current = current.Left;
                if (current == null)
                {
                    parent.Left = newNode;
                    return;
                }
            }
            else
            {
                current = current.Right;
                if (current == null)
                {
                    parent.Right = newNode;
                    return;
                }
            }
        }
    }

    static void Main()
    {

        var tree = new BSTree();
        var numbers = new int[] { 10, 18, 3, 8, 12, 2, 7 };
        foreach (var number in numbers)
        {
            tree.Insert(number);
        }
        tree.Display();
        var node = tree.Find(8);
    }
}

 

2