Monday, May 24, 2010

Can someone look over my C++ function?

Hey guys just want to bounce my algorithm of someone else to see if what I am thinking is correct.





I have a binary tree and I want to swap the sub trees of the tree. So my root node is called "root". The root node is made up of basically a variable to hold the data and a left pointer "llink" that points to the left subtree and a right pointer "rlink" that points to the right subtree.





Ok so my function is here:





template%26lt;class elemType%26gt;


void binaryTreeType%26lt;elemType%26gt;::swapSubTrees


{


nodeType Temp;


Temp = new nodeType;





Temp = root-%26gt;llink;


root-%26gt;llink = root-%26gt;rlink;





root-%26gt;rlink = Temp;


delete Temp;


}





Does this function look like it will accomplish what I want it to do?? The reason I dont test it out myself is because I have to write all the other functions for the tree but I just wanted to make sure that this works first,





Thanks!

Can someone look over my C++ function?
well, the best way to test it is to write a small test function which just uses this function, and afterwards you check the result. this is called a unittest, and it's a great concept, because you can run this test whenever you changed the code, and always can be sure that this function still works.





anyway, it's not ok. first of all, root-%26gt;llink or root-%26gt;rlink can be NULL, and then you should swap a NULL pointer, and not an allocated object.





also, nodeType must be a pointer, otherwise you can't allocate it with new.





also, you delete Temp (in the last line of the function), which means that root-%26gt;rlink is deleted, because root-%26gt;rlink points to Temp.





also, i just saw that you're actually allocating new objects, but that's not necessary.





the correct code would be this (assuming that nodeType is a pointer):





nodeType Temp=root-%26gt;llink;


root-%26gt;llink=root-%26gt;rlink;


root-%26gt;rlink=Temp;





that should be enough. or just use std::swap (in %26lt;algorithm%26gt;), which basically does the same.
Reply:yes it will work


No comments:

Post a Comment