Binary Search Tree remove() function

Im working on a BST remove function. I think I'm on the right track but I'm not sure. From what I understand there are 3 possible cases. A Node with no children, one child, or 2 children(this being the most complex). Can anyone tell me if im on the right track? Thanks for the help.

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
void BST::remove(int x)
{
	TreeNode *n;
	TreeNode *v;
	n= root;
	while(n != NULL && n->key != x){
		if(n->key > x){
			v = n;
			n = n->left;
		}
		if(n->key < x){
			v = n;
			n = n->right;
		}
	}
	if(n->key == x){
		if(n->right == NULL && n->left == NULL){
			v->right = NULL;
			v->left = NULL;
		}
		if(n->right != NULL && n->left == NULL){
			v->right = n->right;
		}
		if(n->right == NULL && n->left != NULL){
			v->left = n->left;
		}
		if(n->right != NULL && n->left != NULL){
			 TreeNode *temp = n->right;
                        TreeNode *othertemp;
			while(temp->left != NULL){
			othertemp = temp;
                        temp = temp->left;
			}
			n->key = temp->key;
            othertemp->left = NULL;
		}
	}
}
Hmm, Looks like you didn't consider the case where x (which I believe is the key) doesn't exist in the tree.
Thanks for the reply. I assumed that line 16 would take care of that. It would only go into those cases if x did exist.
You are on the right track. As algorithm help, take a look at:

http://www.cs.princeton.edu/~rs/AlgsDS07/08BinarySearchTrees.pdf
You are not freeing memory as you should, removing link to a node does not mean it is "removed" from memory and this is what you should be doing
Topic archived. No new replies allowed.