C++ - printing a binary tree vertically, Depth first
The order in which you're traversing the tree is a simple pre-order traversal. If you can use recursion, it's a much easier way to do this traversal:

void preorder(node *root) { 
    if (root == nullptr)
        return;
    std::cout &lt;&lt; root-&gt;val &lt;&lt; " ";
    preorder(root-&gt;left);
    preorder(root-&gt;right);
}


Other than that, your code currently has undefined behavior--in main you don't seem to be allocating any actual nodes for your tree. You're just taking an uninitialized pointer (root) and overwriting whatever happens to be in the memory it points at. To get something meaningful, you need to allocate your nodes.

I'd probably add a constructor to node to make construction a little easier:

struct node {
    int val;
    node *left, *right;

    node(int val) : val(val), left(nullptr), right(nullptr) {}
};


Then main would look something like this:

int main() { 
    node *root = new node(5);
    root-&gt;left = new node(3);
    root-&gt;left-&gt;left = new node(7);
    root-&gt;left-&gt;right = new node(8);
    root-&gt;right = new node(4);
    root-&gt;right-&gt;left = new node(9);
    root-&gt;right-&gt;right = new node(1);
    preorder(root);
    // possibly code here to delete the nodes of the tree.
}