当前位置: 代码迷 >> java >> 去除二叉树中的叶子
  详细解决方案

去除二叉树中的叶子

热度:49   发布时间:2023-07-16 17:55:27.0

我很困惑为什么我的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]

有人可以解释为什么这不符合预期吗?

在示例树中,请考虑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

说地址80XABCD ,所以node = 0XABCD node.data=0因为node具有地址0XABCD0XABCD.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.
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;
}
  相关解决方案