Iterative InOrder Tree Traversal 2 (C++)

Found this from another website, http://www.ihas1337code.com. It’s so much cleaner.

void iterativeInOrderTraverse2(Node *root) {
  stack<Node *> nodes;
  Node *currNode = root;
  while(!nodes.empty() || currNode) {
    if (currNode) {
      nodes.push(currNode);
      currNode = currNode->left;
    }
    else {
      currNode = nodes.top();
      nodes.pop();
      printf("%c ", currNode->data);
      currNode = currNode->right;
    }
  }
}
Advertisements
This entry was posted in Coding and tagged , , . Bookmark the permalink.

2 Responses to Iterative InOrder Tree Traversal 2 (C++)

  1. Barney says:

    How about this ?

    void stack_inorder(struct tree_node* root)
    {
    static stack S;
    static int leaf= 0;
    S.push(root);
    while(S.size()!=0)
    {
    struct tree_node* k = S.top();
    if(k)
    {
    if(k->left && !leaf)
    {
    S.push(k->left);
    }
    else
    {
    leaf=0;
    S.pop();
    printf(“%d “,k->data);
    if(k->right)
    {
    S.push(k->right);
    }
    else
    {
    leaf=1;
    }
    }
    }
    else
    {
    break;
    }
    }

    }

    • fangstar says:

      I don’t think that works. I’m not sure how you’re getting to the left node. If I saw that one an interview test I would not be impressed. There’s no need to test for a var like leaf.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s