-
October 20th, 2009, 01:50 PM
#1
PreOrder Binary Tree HELP!
Hi all. So I have to build a binary tree using the pre order method. I am passing one value at a time to my Insert() function and building it for each value passed. It's confusing me how I would build the function as I'm sort of new to recursion. Any help would be greatly appreciated. I have my Insert() function which compiles but is logically wrong. It works fine up until it reaches the end of the left tree path, then screws everything up from there. I should let you know that if the user inputs -1, this means it is NULL. (The terminal/leaf nodes)
void Insert(treeNode *&ptr, int nodeVal)
{
if (ptr == NULL)
ptr = new treeNode(nodeVal);
else if(ptr->data == -1)
return;
else
{
Insert(ptr->left, nodeVal);
Insert(ptr->right, nodeVal);
}
}
-
October 20th, 2009, 01:57 PM
#2
Re: PreOrder Binary Tree HELP!
PreOrder and PostOrder and InOrder for that matter are used for traversing a tree and not while building it.
How exactly do you want to arrange it when you mean PreOrder and PostOrder insertions?
You will first need to create a chart on which you should draw how the tree should look like when entering values in some predefined order.
Then you should be able to figure out better on how it will work.
-
October 20th, 2009, 02:28 PM
#3
Re: PreOrder Binary Tree HELP!
Your current else case needs to be split up into two cases. After all, you want to insert the new element on one side of the current node or the other; not on both sides.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|