C++/trees with c++
Expert: Eddie - 2/22/2005
Questioni want to make a BST"Binary Search Tree"which i can add,search,print the keys in an ascending order .i'm working on visualc++
plz if u can send me a code today i will owe u.
thx alot
AnswerHello yosr eman, thank you for the question.
The binary search tree is not too difficult of a data structure to code if you understand what is going on conceptually. You say you want to print the values in ascending order, so that would be nothing more than a breadth first traversal since thats how the information is stored in a binary search tree.
So, think about the AddToTree function. You need to traverse this tree either down the left or right branch until you come to a NULL node you can use. So, a good add function would be recursive, and take in 2 nodes as parameters. Being recursive, the first parameter would probably be the root when called the first time. The second node would be the node you want to add to the tree.
A clear function could be easily written recursively to traverse the tree and delete each node. Since it is a simple function, I will show you some example code although we experts here don't usually type people's code for them.
void ClearTree(Node *node)
{
if(!node)
return;
clear(node->leftChild);
clear(node->rightChild);
delete node;
}
See, it's not so bad. If you understand the concept, then coding it isn't a big deal at all.
I hope this information was helpful.
- Eddie