问题描述
我很困惑为什么我的BST中的叶子移除方法不起作用。 如果我将0分配给数据,它会反映在树中,但是当我为节点指定null时,它仍然能够在BST遍历中被引用。
public void removeLeaves(){
removeLeaves(getRoot());
}
private void removeLeaves(IntTreeNode node) {
if (node == null)
return;
else if( node.left == null && node.right == null){
node.data = 0; //im finding the leave nodes correctly
node = null; //but its not removing them
}
else {
removeLeaves(node.left);
removeLeaves(node.right);
}
}
overallRoot
____[7]____
/ \
[3] [9]
/ \ / \
[0] [0] [0] [8]
\
[0]
有人可以解释为什么这不符合预期吗?
1楼
在示例树中,请考虑9
9.left => null
9.right => address of 8
当你指定node.data = 0;
,节点的地址为8
因此0
将反映在树中。
但是当你执行node =null
,你只是在改变变量node
。
你没有address of 8
进行任何操作。
我认为你希望发生的是做node = null
是:
address of 8 = null
这实际上是不可能的,因为你只是在改变变量node
。
说地址8
是0XABCD
,所以node = 0XABCD
。
当node.data=0
因为node
具有地址0XABCD
, 0XABCD.data
将更改为0
。
但是当你执行node = null
,你只是为变量node
分配一个新值,你没有对原始地址0XABCD
进行任何操作。
你实际需要做的是
if(node.left!= null && node.left.left == null && node.left.right ==null)
node.left =null
if(node.right!= null && node.right.left == null && node.right.right ==null)
node.right =null
UPDATE
你要做的是这样的事情:
Foo foo = new Foo();
Foo anotherFoo = foo;
anotherFoo.value = something; // both foo.value and anotherFoo.value will be changed to "something", because of the reference.
anotherFoo = null;
// here you are expecting foo also to be null which is not correct.
2楼
public void removeLeaves () {
if (getRoot() != null)
removeLeaves (getRoot());
}
private IntTreeNode removeLeaves (IntTreeNode node) {
if (getRoot().left == null && getRoot().right == null) {
setRoot(null);
} else {
if (node.left != null) {
if (node.left.left == null && node.left.right == null)
node.left = null;
else
removeLeaves(node.left);
}
if (node.right != null) {
if (node.right.right == null && node.right.left == null)
node.right = null;
else
removeLeaves(node.right);
}
}
return node;
}