CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Oct 2009
    Posts
    11

    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);
    }
    }

  2. #2
    Join Date
    Feb 2009
    Location
    India
    Posts
    444

    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.
    «_Superman
    I love work. It gives me something to do between weekends.

    Microsoft MVP (Visual C++)

  3. #3
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    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
  •  





Click Here to Expand Forum to Full Width

Featured