简体   繁体   中英

Removal not working for BST in java

I'm writing a code for implementing BST in java. My insert, search, search for inorder successor, inorder traversal work fine but when I remove a node, it is not actually removed. Consider the simplest case where the node to be removed is a pendant node. Even if I set this node to null, it is still printed in inorder traversal after deletion. Can anyone please help?
Thank you.

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);
    }
}

Setting delnode = null does nothing: you have a local copy of the reference to a node, and you changed it to refer to null . That doesn't change the actual node in memory at all.

Instead, you must find its parent and set that parent's left or right reference (depending on which is the node to delete) to null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM