Help me understand Inorder Traversal without using recursion

后端 未结 14 2723
别跟我提以往
别跟我提以往 2020-12-12 11:44

I am able to understand preorder traversal without using recursion, but I\'m having a hard time with inorder traversal. I just don\'t seem to get it, perhaps, because I have

14条回答
  •  甜味超标
    2020-12-12 12:34

    Here's an iterative C++ solution as an alternative to what @Emadpres posted:

    void inOrderTraversal(Node *n)
    {
        stack s;
        s.push(n);
        while (!s.empty()) {
            if (n) {
                n = n->left;
            } else {
                n = s.top(); s.pop();
                cout << n->data << " ";
                n = n->right;
            }
            if (n) s.push(n);
        }
    }
    

提交回复
热议问题