我需要刪除最小值的二叉搜索樹,但我找不到一個乾淨的方式來做到這一點,目前我有一種乾淨的代碼,雖然它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,但我的主根元素不會更改其任何節點 - 我期望它的工作方式,任何解決方法?
您將本地變量tempElement設置爲null,但不設置root的字段。很顯然,root並沒有改變。 – kaitoy