簡體   English   中英

二叉搜索樹Tree Implementation,程序終止於Eclipse。 簡單的插入和顯示操作

[英]Binary search tree Tree Implementation, Program terminates in eclipse. simple insert and display operation

這是一個僅用於實現二進制搜索樹的類Trees ,無法理解這是怎么回事。

public class Trees {

    static Node root = null;

    static void insert(int data, Node r)
    {
        if(r==null)
        {
            r = new Node();
            r.data = data;
            r.left = null;
            r.right=null;
        //  System.out.println(root.data);
        }

        else
        {   
            Node current;
            current = r;

            if(data >=current.data)
                {
                insert(data,current.right);
                }

            else if(data < current.data)
            {
            insert(data,current.left);
            }
        }
    }


    static void display(Node r)
    {

       if(r!=null)
       {

        display(r.left);
        display(r.right);
        System.out.print(r.data +"  ");

       }

    }

    public static void main(String[] args) {

        insert(2, root);
        insert(6, root);
        insert(1, root);
        insert(5, root);

        display(root);

    }

}

這可能是什么問題?

public class Trees {

static Node root = null;

static Node insert(int data, Node r)
{
    if(r==null)
    {
        r = new Node();
        r.data = data;
        r.left = null;
        r.right=null;
        return r;
    //  System.out.println(root.data);
    }

    else
    {   

    Node current=r;
        if(data >=current.data)
            {
          current.right= insert(data,current.right);
            }

        else if(data < current.data)
        {
        current.left=insert(data,current.left);
        }
    }
    return r;

}


static void display(Node r)
{

   if(r!=null)
   {

    display(r.left);
    display(r.right);
    System.out.print(r.data +"  ");

   }

}

public static void main(String[] args) {

    root=insert(2, root);
    root=insert(6, root);
    root=insert(1, root);
    root=insert(5, root);

    display(root);

}

}

class Node
{
     public int data;
     public Node left;
     public Node right;
}

這段代碼是有效的,如果要使用遞歸,則還必須將引用的值分配給引用變量。 嘗試使用此代碼,該代碼也可以正常工作並打印輸出。

代碼輸出

          I hope I helped you.

問題是您的代碼根中從未分配。 這就是為什么它在返回r並在另一個答案中分配給root的代碼中起作用的原因。

static void insert(int data, Node r)
{
    if(r==null)
    {
        r = new Node();
        r.data = data;
        r.left = null;
        r.right=null;
    //  System.out.println(root.data);
    }
    ....
 }

那if塊實際上沒有任何用處。 “ r”不會通過引用傳遞到函數中,因此對“ r”的賦值不會傳播回根變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM