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

    data srtructire-Tree traversal

    We are given a binnary tree, we have to do inorder traversal and postorder traversal.

    Waht i have done is

    Inorder traversal
    1, 2 ,3 ,4 ,5, 6, 7, 8,9 , 10, 11, 12, 13 ,14 , 18

    Postorder traversal
    1,2, 6, 7,9,8,5,11, 10,12, 4, 3, 13, 18,14

    Please correct me. The BST is in the attachment.
    Attached Files Attached Files

  2. #2
    Join Date
    Mar 2009
    Posts
    19

    Re: data srtructire-Tree traversal

    For a valid binary tree, an in-order traversal will always result in a strictly non-descending order, so yours is correct.

    In a postorder traversal, you visit both your children before you visit yourself. Therefore, yours is wrong right off the bat because 1 must come after 2, since 2 is a child of 1.

    Code:
    void visit_node(Node * node)
    {
        if(!node)
            return;
    
        visit_node(node->left);
        visit_node(node->right);
        //do something with node's val, like print it
        std::cout << node->val;
    }
    That's all there is to it. Just follow that down to get your order.

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