集册 Java实例教程 创建二叉搜索树

创建二叉搜索树

欢马劈雪     最近更新时间:2020-01-02 10:19:05

497
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
创建二叉搜索树

class BinarySearchTree

{

    node head;
    /*
     from 时 代 J a v a 公 众 号 
    */


    static class node

    {

        int data;

        node left;

        node right;


        node(int d)

        {

            data = d;

            left = null;

            right = null;/**来自 NowJava.com - 时代Java**/

        }

    }


    public void Insert(int value)

    {

        node temp = new node(value);


        if(head == null)

            head = temp;

        else

        {

            node current;

            current = head;


            while(current != null)

            {

                if(value < current.data)

                {

                    if(current.left != null)

                        current = current.left;

                    else

                    {

                        current.left = temp;

                        return ;

                    }

                }

                else

                {

                    if(current.right != null)

                        current = current.right;

                    else

                    {

                        current.right = temp;

                        return ;

                    }

                }

            }

        }

    }


    public void Search(int value)

    {

        node current;

        current = head;


        while(current != null)

        {

            if(value < current.data)

                current = current.left;

            else if(value > current.data)

                current = current.right;

            else

            {

                System.out.println("Element " + value + " Found");

                return ;

            }

        }


        System.out.println("Element " + value + " not Found");

    }


    public int Min_Value(node head)

    {

        while(head.left != null)

        {

            head = head.left;

        }

        return head.data;

    }


    public node Delete_Key(node head, int value)

    {

        if(head == null)

            return head;


        if(value < head.data)

            head.left = Delete_Key(head.left, value);

        else if(value > head.data)

            head.right = Delete_Key(head.right, value);

        else

        {

            if(head.left == null)

                return head.right;

            else if(head.right == null)

                return head.left;


            head.data = Min_Value(head.right);

            head.right = Delete_Key(head.right, head.data);

        }


        return head;

    }


    public 
展开阅读全文