sudhanshu
sudhanshu

Reputation: 19

Deleting a node in Binary Search Tree

I made a function to delete a node from BST. I was wondering if the two recursive codes do the same thing or not

BstNode* temp = new BstNode();
temp = root;
delete(root);
return temp->left;
return root->left;

I know that the first one deletes root from the heap memory but it adds temp to the memory so is it same as the second code?

Upvotes: 0

Views: 63

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123431

Sorry, but it has to be said clear: This code makes no sense whatsoever.

BstNode* temp = new BstNode();   // (1)
temp = root;                     // (2)
delete(root);                    // (3)
return temp->left;               // (4)

(1) dynamically allocates a BstNode. After assigning root to temp in (2) the memory allocated in (1) is leaked. You lost any reference to it.

Then (3) deletes root but temp points to the same, it has the same value as root because of the assignment in (2). Hence (4) is undefined behavior due to dereferencing a dangling pointer.

This code is no good.

On the other hand this:

return root->left;

dereferences root and returns its left member. If root is a valid pointer this code is not causing same desaster as the first.

Upvotes: 2

Related Questions