Can't delete nodes from a BST?

Hello all,

I'm implementing a binary search tree from scratch to get a good feel for everything, and all of the functions work except for merge by copying. Actually, it does work when the the node to be deleted has two children, so the problem lies in the two lines

node = node->left;
and
node = node->right;
, which are commented in the code.

This is actually the code as my book has it written, and I don't see why it doesn't move all children up one node in the tree, replacing node with node's left child, or with its right child, depending. It seems to be a pretty simple way to delete a node with only one child. Am I looking at this the wrong way? I can post all code if desired. As usual, thanks in advance for any help or tips!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
void BST::findToDel(int k){
		Node *temp = root;
		Node *prev = root;
		Node *node;
		while(true){
			if(temp->getKey() == k){
				node = temp;
				break;
			}
			else if(k < temp->getKey()){
				prev = temp;
				temp = temp->left;
			}
			else if(k > temp->getKey()){
				prev = temp;
				temp = temp->right;
			}
			else if(temp == 0){
				cout << "\nUh-oh, not found.";
				return;
			}
		}
			if(node->right == 0)
			node = node->left;  //why does this not overwrite?
			else if(node->left == 0)
			node = node->right;  //why does this not overwrite?
			else{
			Node *temp = node->left;
			Node *prev = node;
			while(temp->right != 0){
				prev = temp;
				temp = temp->right;
			}
			node->setKey(temp->getKey());
			if(prev == node)
				prev->left = temp->left;
			else
				prev->right = temp->left;
			delete temp;
		}

	}
Topic archived. No new replies allowed.