C++ - printing a binary tree vertically, Depth first eg:
   5
  / \
 3   4
/\   /\
7 8  9 1

should print: 5 3 7 8 4 9 1


#include &lt;iostream&gt;
include &lt;stack&gt;
using namespace std;`

class node{
public:
int val;
node* left;
node* right;
bool istraversed=false;
};


void printdfs(node* root){
stack&lt;node*&gt; s;
s.push(root);

while(!s.empty()){

    node *temp = s.top();
    if(temp-&gt;istraversed==false){
        cout&lt;&lt;temp-&gt;val&lt;&lt;" "; 
        temp-&gt;istraversed=true;
    }
    if(temp-&gt;left!=NULL){
        if(temp-&gt;left-&gt;istraversed==false){
            s.push(temp-&gt;left);
            continue;
        }
    }
    if(temp-&gt;right!=NULL){
        if(temp-&gt;right-&gt;istraversed==false){
            s.push(temp-&gt;right);
            continue;
        }
    }
    s.pop();
}    
}


int main() {

node* root;
root-&gt;val=1;
cout&lt;&lt;root-&gt;val&lt;&lt;",";

root-&gt;left-&gt;val = 2;
cout&lt;&lt;root-&gt;left-&gt;val&lt;&lt;",";
root-&gt;right-&gt;val = 3;
cout&lt;&lt;root-&gt;right-&gt;val&lt;&lt;",";

root-&gt;left-&gt;left-&gt;val=4;
cout&lt;&lt;root-&gt;left-&gt;left-&gt;val&lt;&lt;",";
root-&gt;left-&gt;right-&gt;val=5;
cout&lt;&lt;root-&gt;left-&gt;right-&gt;val&lt;&lt;",";
root-&gt;right-&gt;left-&gt;val=6;
root-&gt;right-&gt;right-&gt;val=7;
root-&gt;left-&gt;left-&gt;left-&gt;val=8;

printdfs(root);

return 0;


}
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.
}