inorder and preorder traversal code example
Example: preorder traversal
#include
using namespace std;
class node{
public:
int data;
node* left;
node* right;
node(int d){
data = d;
left = NULL;
right = NULL;
}
};
node* buildTree(){
int d;
cin>>d;
if(d==-1){
return NULL; //to attach a NULL pointer[in case of no child] enter -1
}
node * root = new node(d);
root->left = buildTree();
root->right = buildTree();
return root;
}
//REQUIRED FUNCTION: Inorder Traversal
void printIn(node*root){
if(root==NULL){
return;
}
//Otherwise Left Root Right
printIn(root->left);
cout<data<<" ";
printIn(root->right);
}
int main(){
node* root = buildTree();
printIn(root);
return 0;
}
//SAMPLE INPUT TO RUN THE CODE ON ANY ONLINE IDE:
//8 10 1 -1 -1 6 9 -1 -1 7 -1 -1 3 -1 14 13 -1 -1 -1