2016-11-21 87 views
0

我需要刪除最小值的二叉搜索樹,但我找不到一個乾淨的方式來做到這一點,目前我有一種乾淨的代碼,雖然它doesn 「T工作,我期望它的工作,我有這個代碼(MTE MTE了左,右MTE和INT VAL鍵):設置參考對象密鑰爲空不能正常工作

MTE tempElement = root; 

if(root == null) return; 
else if((root.left == null) && (root.right == null)) 
{ 
    root = null; 
    return; 
} 
else if(root.left != null) 
{ 
    while(tempElement.left != null) tempElement = tempElement.left; 

    if(tempElement.right == null) tempElement = null; 
    else tempElement = tempElement.right; 
} 
else if(root.right != null) 
{ 
    if(tempElement.left == null) root = tempElement; 
    else 
    { 
     while(tempElement.left != null) tempElement = tempElement.left; 

     root.val = tempElement.val; 
     if(tempElement.right == null) tempElement = null; 
     else tempElement = tempElement.right; 
    } 
} 

我這段代碼有問題是,當我得到這個代碼行 - if(tempElement.right == null) tempElement = null;這是我提供的代碼片段中的第13行。當我調試它時,它將tempElement更改爲null,但我的主根元素不會更改其任何節點 - 我期望它的工作方式,任何解決方法?

+0

您將本地變量tempElement設置爲null,但不設置root的字段。很顯然,root並沒有改變。 – kaitoy

回答

3

你應該繼續保留指向父節點,然後更改父節點的左或右指針,例如

if(root.left != null) 
{ 
    MTE prev = tempElement; 
    while(tempElement.left != null) { 
     prev = tempElement; 
     tempElement = tempElement.left; 
    } 

    if(tempElement.right == null) prev.left = null; 
    else prev.left = tempElement.right; 
} 

需要做的同樣對於!= null也是如此。

+0

謝謝,炒鍋像魅力。 – dnc123

0

您的leftright字段是參考變量。他們可以持有對象的引用。

您的變量tempElement是一個局部變量。最初它擁有一個對象引用的副本。 它不保存對其值被複制的字段的引用。當您將該局部變量設置爲null時,就是發生這種情況。

如果要將對象中的字段設置爲null,則必須將該字段分配給該字段,而不是分配給恰好包含對同一對象的引用副本的局部變量。例如,這將某個字段設置爲NULL:

tempElement.left = null;