//
// main.cpp
// Depth First Traversal in Binary Tree
//
// Created by Himanshu on 26/08/21.
//
#include <iostream>
#include <queue>
using namespace std;
struct node {
int value = 0;
struct node *left, *right;
};
typedef struct node Node;
node* newNode(int data)
{
node* Node = new node();
Node->value = data;
Node->left = NULL;
Node->right = NULL;
return(Node);
}
void inorder (Node *root) {
if (root == NULL) {
return;
}
// traverse left
inorder (root->left);
// print root
cout << root->value << " ";
// traverse right
inorder (root->right);
}
void preorder (Node *root) {
if (root == NULL) {
return;
}
// print root
cout << root->value << " ";
// traverse left
preorder (root->left);
// traverse right
preorder (root->right);
}
void postorder (Node *root) {
if (root == NULL) {
return;
}
// traverse left
postorder (root->left);
// traverse right
postorder (root->right);
// print root
cout << root->value << " ";
}
int main() {
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->right->left = newNode(4);
root->right->right = newNode(5);
cout<<"Inorder traversal:"<<endl;
inorder (root);
cout<<endl;
cout<<"Preorder traversal:"<<endl;
preorder (root);
cout<<endl;
cout<<"Postorder traversal:"<<endl;
postorder (root);
cout<<endl;
return 0;
}
Ly8KLy8gIG1haW4uY3BwCi8vICBEZXB0aCBGaXJzdCBUcmF2ZXJzYWwgaW4gQmluYXJ5IFRyZWUKLy8KLy8gIENyZWF0ZWQgYnkgSGltYW5zaHUgb24gMjYvMDgvMjEuCi8vCgojaW5jbHVkZSA8aW9zdHJlYW0+CiNpbmNsdWRlIDxxdWV1ZT4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCnN0cnVjdCBub2RlIHsKICAgIGludCB2YWx1ZSA9IDA7CiAgICBzdHJ1Y3Qgbm9kZSAqbGVmdCwgKnJpZ2h0Owp9Owp0eXBlZGVmIHN0cnVjdCBub2RlIE5vZGU7Cgpub2RlKiBuZXdOb2RlKGludCBkYXRhKQp7CiAgICBub2RlKiBOb2RlID0gbmV3IG5vZGUoKTsKICAgIE5vZGUtPnZhbHVlID0gZGF0YTsKICAgIE5vZGUtPmxlZnQgPSBOVUxMOw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