2016-11-21 65 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;