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?
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.
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.