eg:
5
/ \
3 4
/\ /\
7 8 9 1
should print: 5 3 7 8 4 9 1
#include <iostream>
include <stack>
using namespace std;`
class node{
public:
int val;
node* left;
node* right;
bool istraversed=false;
};
void printdfs(node* root){
stack<node*> s;
s.push(root);
while(!s.empty()){
node *temp = s.top();
if(temp->istraversed==false){
cout<<temp->val<<" ";
temp->istraversed=true;
}
if(temp->left!=NULL){
if(temp->left->istraversed==false){
s.push(temp->left);
continue;
}
}
if(temp->right!=NULL){
if(temp->right->istraversed==false){
s.push(temp->right);
continue;
}
}
s.pop();
}
}
int main() {
node* root;
root->val=1;
cout<<root->val<<",";
root->left->val = 2;
cout<<root->left->val<<",";
root->right->val = 3;
cout<<root->right->val<<",";
root->left->left->val=4;
cout<<root->left->left->val<<",";
root->left->right->val=5;
cout<<root->left->right->val<<",";
root->right->left->val=6;
root->right->right->val=7;
root->left->left->left->val=8;
printdfs(root);
return 0;
}