2013-09-25 26 views
1

我剛剛瞭解二叉樹,我試圖創建一個插入方法。我的第一種方法不起作用,我做了一些調整。它現在可以工作,但我不明白爲什麼以前的方法失敗。二叉樹:爲什麼一個插入方法的工作和其他不是

不工作的方法是:

if(root == null) 
    { 
     root = new Node(data); 
    } 
    else if(data < root.getData()) 
    { 
     insertNode(root.getLeft(), data); 
    } 
    else 
    { 
     insertNode(root.getRight(), data); 
    } 

,它的工作方法:

if(data < root.getData()) 
    { 
     if(root.getLeft() == null) 
     { 
      root.left = new Node(data); 
     } 
     else 
     { 
      insertNode(root.getLeft(), data); 
     } 
    } 

    else 
    { 
     if(root.getRight() == null) 
     { 
      root.right = new Node(data); 
     } 
     else 
     { 
      insertNode(root.getRight(), data); 
     } 
    } 

任何解釋,爲什麼出現這種情況?因爲我看到它的方式,root應該等於root.left,因此將root設置爲新節點應該與將root.left/right設置爲新節點相同。

+1

第二個代碼中的異常/問題是什麼?我沒有看到第二個代碼中的根空值檢查。在這種情況下,你不能在第一個代碼中插入第一個元素 – JohnnyAW

+0

@JohnnyAW:他調用insertNode(null,data),這是行不通的。但我還需要一些時間來得到它^^ –

+0

@ user2776326我認爲你的第二個代碼有問題,因爲在root爲空的情況下,它將如何與數據進行比較? –

回答

2

在你的第一個方法中,你將null賦值給你的insertNode方法,但是沒有引用指針。因此,您在insertNode方法中設置了root = new Node(),但父節點不知道任何這一點,它仍然指向null。由於這是一些非常基本的Java理解,所以我推薦閱讀一些關於「java參數傳遞」的文章,例如http://javadude.com/articles/passbyvalue.htm

+1

謝謝,我想我明白了。所以從我收集的內容中,Java將值null傳遞給參數,所以本質上我們得到insertNode(null,data),並且沒有對root.right/left的引用。那是對的嗎? – user2776326

+1

好的答案,如果我是操作者,我會接受它。 –

+0

@ user2776326:是的,你理解正確。 –

0

假設你遞歸調用該方法,insertNode(root, data),你必須要確保rootnull,這意味着執行root = new Node(data);創建一個對象,它的知名度僅限於insertNode方法。

如果不是,則可以將insertNode(data)重寫爲非遞歸,如果它是null,則可以在其內部創建root

public void insert(int data) { 
    if(root == null){ 
     root = new Node(data); 
    } 
    else { 
     Node current = root; 
     Node previous; 
     String from; 
     while(current != null) { 
      previous = current; 
      if(data < current.getData()) { 
       current = current.left(); 
       from = "left"; 
      } 
      else { 
       current = current.right(); 
       from = "right"; 
      } 
     } 
     current = new Node(data); 
     if(from.equals("left")) { 
      previous.left() = current; 
     } else { 
      previous.right() = current; 
     } 
    } 
}