Tree: Preorder Traversal

  • + 0 comments

    C++, iterative with a stack instead of recursive. We visit each node, then push its right and then left (in reverse order) so they are visited in the correct order as we later pop the stack.

    The Hackerrank solution code doesn't include <vector> which you kinda need, so I hacked a way to get it included. Here's the full text of my solution, verbatim (it intentionally ends with an open brace).

        void preOrder(Node *root);
    };
    #include <vector>
    #include <utility>
    
    void Solution::preOrder(Node* root) {
        std::vector<Node*> stack;
        
        stack.reserve(20);
        
        stack.push_back(root);
        while (!stack.empty()) {
            auto node = stack.back();
            stack.pop_back();
            std::cout << node->data << ' ';
            if (node->right)
                stack.push_back(node->right);
            if (node->left)
                stack.push_back(node->left);
        }
    }
    
    struct HACK {