Thread: Deleting from a Binary Search Tree

  1. #1

    Deleting from a Binary Search Tree

    I have this deletion code that doesn't fully work, and I have no idea how to fix it:

    Code:
    bool BINARYTREE::deleteByNode(BNODE* nodePtr) {
    	bool ret = false;   
      
    	if (nodePtr != NULL) 
    	{
    		if (nodePtr->isLeaf()) 
    		{ 
     			if (parent != NULL)
    			{
    				if (parent->getLeft() == nodePtr)
    					parent->setLeft(NULL);
    				else
    					parent->setRight(NULL);
    			}
    			delete nodePtr;
    
    			if (nodePtr == root)
    				root = NULL;
    
    			ret = true;
    		} else {
    			if (nodePtr->getLeft()) 
    			{     
    				BNODE* temp = nodePtr->getLeft();
    				BNODE* tempParent = nodePtr;
    
    				while(temp->getRight()!= NULL) 
    				{
    					tempParent = temp;
    					temp = temp->getRight();
    				}
    
    				nodePtr->setData(temp->getData());
    				ret = true;
               
    				if(temp->getData() > tempParent->getData())
    				{
    				   tempParent->setRight(NULL);
    				   tempParent->setLeft(temp->getLeft());
    				}
    				else
    				   tempParent->setLeft(NULL);
    
    				delete temp;
    
    			} else { 
    				   nodePtr->setData(nodePtr->getRight()->getData());
    				ret = true;
                                    parent = nodePtr;
    				deleteByNode(nodePtr->getRight());
    			}
    		}
    	}
        
    	return(ret);
    }
    This code works with some trees like: 1, 3, 32, -1
    but with a tree like 1, 0, -2

    it crashes :'( because every node is the the left of every other node.

    If anyone can help I'd appreciate it. I'm not usre about the attachment rules, but if you downloadthe attachment, just rename it to a .zip extension and unzip it to get all of my code. I'm sorry if this violates any rules.

    Thanks,
    Sean
    Last edited by unanimous; 04-16-2006 at 12:24 PM. Reason: Add more information

  2. #2
    Nevermind I found it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Binary search needed
    By ItsMeHere in forum C Programming
    Replies: 1
    Last Post: 06-22-2006, 07:26 AM
  2. BST (Binary search tree)
    By praethorian in forum C++ Programming
    Replies: 3
    Last Post: 11-13-2005, 09:11 AM
  3. Binary Tree, couple questions
    By scoobasean in forum C Programming
    Replies: 3
    Last Post: 03-12-2005, 09:09 PM
  4. Binary Search Tree, Inserting node
    By cheryl_li in forum C Programming
    Replies: 1
    Last Post: 09-13-2003, 03:53 AM
  5. BST/Red and Black Tree
    By ghettoman in forum C++ Programming
    Replies: 0
    Last Post: 10-24-2001, 10:45 PM