【问题标题】:Removal not working for BST in java删除不适用于 java 中的 BST
【发布时间】:2014-11-12 22:08:21
【问题描述】:

我正在编写用于在 java 中实现 BST 的代码。我的插入、搜索、搜索中序后继、中序遍历工作正常,但是当我删除一个节点时,它实际上并没有被删除。考虑最简单的情况,其中要删除的节点是一个挂件节点。即使我将此节点设置为null,删除后仍会以中序遍历打印。谁能帮忙?
谢谢。

package pack_l;

class BSTNode
{
  int key;
  BSTNode left;
  BSTNode right;

  BSTNode(int key)
  {
    this.key = key;
    this.left = this.right = null;
  }
}

class BST
{
  BSTNode root;

  BST()
  {
    root = null;
  }

  /*insert a node at proper position*/
  void insert(BSTNode n)
  {
    if(root == null)
      root = n;
    else
    {
      BSTNode node = root;
      while(node != null)
      {
        if(node.key > n.key)
        {
          if(node.left == null)
          {
            node.left = n;
            return;
          }
          else 
            node = node.left;
        }                   
        else
        {
          if(node.right == null)
          {
            node.right = n;
            return;
          }
          else 
            node = node.right;  
        }
      }/*End of while-loop*/
    }
  }

  /*Search a node in the whole tree*/
  BSTNode search(int val)
  {
    BSTNode node = root;
    while(node != null)
    {
      if(node.key == val)
        return node;
      else if(node.key > val)
        node = node.left;
      else
        node = node.right;
    }
    return null;
  }

  /*Remove a node from the tree*/
  boolean remove(int val)
  {
    BSTNode delNode = search(val);              

    /*If the node is not in the BST*/
    if(delNode == null)
      return false;

    /*If the node has no child*/
    if(delNode.left == null && delNode.right == null)
      delNode = null;

    return true;
  }

  void inorder(BSTNode root)
  {
    if(root == null)
        return;

    inorder(root.left);
    System.out.print(" " + root.key + " ");
    inorder(root.right);
  }
}

public class BSTree {

public static void main(String[] args) {

    BST tree = new BST();
    BSTNode n1 = new BSTNode(15);
    tree.insert(n1);
    System.out.println("Before:");
    tree.inorder(tree.root);
    tree.remove(15);
    System.out.println("\nAfter:");
    tree.inorder(tree.root);
    }
}

【问题讨论】:

标签: java binary-search-tree


【解决方案1】:

设置delnode = null 没有任何作用:您拥有对节点的引用的本地副本,并且您将其更改为引用null。这根本不会改变内存中的实际节点。

相反,您必须找到它的父节点并将该父节点的左引用或右引用(取决于要删除的节点)设置为 null。

【讨论】:

  • 谢谢,我现在看到了。
  • 还有一个问题,有什么办法可以得到要删除的节点的实际引用?我认为java总是通过引用返回对象。
  • Java 按值传递引用,所以,没有。
  • 您可以通过使用 BSTNode 周围的包装器并将其传递给方法来获取对要删除的节点的引用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多