Thread: c++ binary tree

  1. #1
    Registered User Solarwin's Avatar
    Join Date
    Dec 2012
    Posts
    50

    Unhappy c++ binary tree

    hi, there.
    I am not sure how to build the tree with values:

    Code:
    struct Node *root = 1  root->left        = 2
      root->right       = 3
      root->left->left  = 4;
      root->left->right = 5;
    Everything should be right except the main(). How to demonstrate this program correctly?


    Code:
    #include <iostream>
    #include<stdio.h>
    #include<stdlib.h>
    #include <stack>          // std::stack
    
    using namespace std;
    
    struct Node
    {
        char value;
        Node* left;
        Node* right;
    };
    
    void Visit(Node* node)
    {
        cout << node->value;
    }
    
    void InorderTraversal(Node* root)
    {
        stack<Node*> s;
    
        Node* current = root;
    
        while (current != NULL)
        {
            s.push(current);
            current = current->left;
        }
    
        while (!s.empty())
        {
            current = s.top();
            s.pop();
    
            Visit(current);
    
            current = current->right;
            while (current != NULL)
            {
                s.push(current);
                current = current->left;
            }
        }
    }
    
    int main()
    {
    /* Constructed binary tree is
                1
              /   \
            2      3
          /  \
        4     5
      */
      struct Node *root = 1
      root->left        = 2
      root->right       = 3
      root->left->left  = 4;
      root->left->right = 5;
    
      InorderTraversal(root);
        return 0;
    }

  2. #2
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    We can tell that everything except main was not written by you, and main is very wrong.
    This exercise is too advanced for you. You must first learn about "pointers", "structures" and ideally "dynamic memory allocation".
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  3. #3
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499
    Yes I agree with iMalc and normally I would give someone a huge hint when I know it.

    Somethings to think about in main.

    What you need you must create. What are you sending to
    Code:
    voidInorderTraversal(Node* root)
    ?

    I don't think you need to be using <stack> just yet, learn what is really going on. I am still learning myself, and this is a great site to help a long the way. Also what you create you must destroy and give back to the free store "heap".

  4. #4
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499
    Solarwin like I said I am learning to and now I have a question. Did I clean up correctly? I have recently realized I have a program about forgetting to clean up after myself. Thought this was a good opportunity to check.


    Code:
    void cleanUp(NodePtr head)
    {
        NodePtr Current = head;
        NodePtr Temp = Current;
        
        while (Current != NULL) {
            
            Current=Current->left;
            Temp=Temp->right;
            
            delete Current;
            delete Temp;
        }
    }

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Looks wrong to me. For example, you would not delete the root node since you immediately set the Current node to its left child on the first iteration of the loop. Then, the fact that you delete Current means that the next access to Current->left dereferences a pointer to an object that no longer exists.

    By the way, there's probably no need for NodePtr: just write Node* instead.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499
    Code:
    typedef struct Node
    {
        char value;
        Node* left;
        Node* right;
    }*NodePtr;
    I just prefer this type of style above. Do you think it is confusing?
    Code:
    void cleanUp(NodePtr head)
    {
        NodePtr Current = head;
        NodePtr Temp = head;
        NodePtr trail = head;
        NodePtr trailBuddy=head;
        
        while (Current != NULL) {
            
            Current=Current->right;
            Temp=Temp->left;
            trail=trail->right;
            trailBuddy=trailBuddy->left;
            
            delete Current;
            delete Temp;
        }
    }
    Ok so don't beat me up over the name to much but what I was thinking the temp and current nodes will be deleted and the trail and trail buddy would go to the next before they were deleted.
    Last edited by jocdrew21; 12-30-2013 at 11:45 AM.

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by jocdrew21
    I just prefer this type of style above. Do you think it is confusing?
    Why do you prefer it? We might typedef a pointer to serve as an iterator, but then that's because the name iterator might serve as an interface by convention, and the pointer might later be replaced by a class, e.g., if actually the iterator is not necessarily random access. In this case, your type name alias contains an abbreviation for "pointer", so it seems that you gain nothing from this typedef.

    Quote Originally Posted by jocdrew21
    what I was thinking the temp and current nodes will be deleted and the trail and trail buddy would go to the next before they were deleted.
    The fact that you set Current = Current->left and then delete Current still means that on the next iteration, Current->left dereferences a pointer to an object that has been destroyed.

    Even if you avoided this, your algorithm has a fundamental problem: suppose your binary tree is a complete tree with a height of say, 3. After the immediate children of the root have been destroyed, the left child of the left child of the root will be destroyed, but not the right child. The right child of the right child of the root will be destroyed, but not the left child. So on and so forth.

    I think that you may need an explicit stack in order to use iteration to destroy such a tree (unless you happen to be storing the complete tree in an array, as per the usual heap implementation, but that's not the case here). Alternatively, you could use recursion.
    Last edited by laserlight; 12-30-2013 at 12:01 PM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  8. #8
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499
    Never even thought of recursion... I am not even on this data structure yet but it looks pretty efficient. 0(1)?

    Code:
    void cleanUp(Node* head)
    {
        if (head!=NULL) {
            cleanUp(head->left);
            cleanUp(head->right);
            delete head;
        }
    }

  9. #9
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Quote Originally Posted by jocdrew21 View Post
    Never even thought of recursion... I am not even on this data structure yet but it looks pretty efficient. 0(1)?
    O(N).

    And recursion would make the inorder traversal a snap as well, just a few lines of code quite similar in looks to the cleanUp function with some minor adjustments.

    OP: Are you trying to store/print characters or integers? If you declare that a node holds characters but store integers then when it comes time to print the data out, you aren't going to see 1, 2, 3... etc.. but the ascii characters that those values represent... unless you cast before printing but why do that when you should just change what is being stored from char to integer.
    Last edited by hk_mp5kpdw; 12-30-2013 at 01:44 PM.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Converting From Binary Tree to Threaded Binary Trees
    By elton_fan in forum C Programming
    Replies: 15
    Last Post: 11-08-2007, 11:41 PM
  2. Replies: 2
    Last Post: 08-01-2007, 01:08 PM
  3. Replies: 0
    Last Post: 11-04-2006, 11:07 AM
  4. display tree data in binary tree format
    By xddxogm3 in forum C++ Programming
    Replies: 4
    Last Post: 12-11-2003, 12:47 AM
  5. b-tree (not binary tree) implementation help
    By Unregistered in forum C++ Programming
    Replies: 8
    Last Post: 01-02-2002, 03:30 PM

Tags for this Thread