[英]Setting reference object key to null doesn't work as expected
I need to remove the smallest value of binary search tree but I can't find a clean way to do it, currently I have kind of clean code, though it doesn't work as I expect it to work, I've got this code(MTE got MTE left, MTE right and int val keys): 我需要删除二进制搜索树的最小值,但是我找不到一种干净的方法,目前我有一种干净的代码,尽管它无法正常工作,但我已经知道了代码(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;
}
}
The problem I got with this code is when I get to this line of code - if(tempElement.right == null) tempElement = null;
这段代码的问题是当我到达这行代码if(tempElement.right == null) tempElement = null;
Which is 13th line on the code snippet that I provided. 这是我提供的代码段的第13行。 When I debugged it it changes tempElement to null, but my main root element doesn't change any of its nodes - the way I expected it to work, any workaround? 当我对其进行调试时,它将tempElement更改为null,但是我的主根元素未更改其任何节点-我期望它的工作方式,是否有任何解决方法?
You should hold pointer to the parent node and then change the parent node's left or right pointer, for example 您应保持指向父节点的指针,然后更改父节点的左或右指针,例如
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;
}
Need to do the same for right != null as well. 还需要对正确的!= null做同样的事情。
Your left
and right
fields are reference variables. 你的left
和right
字段引用变量。 They can hold references to objects. 它们可以保存对对象的引用。
Your variable tempElement
is a local variable. 您的变量tempElement
是局部变量。 Initially it holds a copy of a reference to an object. 最初,它保存对对象的引用的副本。 It does not hold a reference to the field from which its value was copied. 它不保存对从中复制其值的字段的引用。 When you set that local variable to null, that's all that happens. 当您将该局部变量设置为null时,便完成了所有操作。
If you want to set a field in an object to null, you have to assign to the field -- not assign to a local variable that happens to hold a copy of the reference to the same object. 如果要将对象中的字段设置为null,则必须分配给该字段,而不是分配给恰好持有对该对象的引用副本的局部变量。 For example, this will set a field to null: 例如,这会将一个字段设置为null:
tempElement.left = null;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.