1#include<iostream>
2using namespace std;
3struct node {
4 int data;
5 struct node *left;
6 struct node *right;
7};
8struct node *createNode(int val) {
9 struct node *temp = (struct node *)malloc(sizeof(struct node));
10 temp->data = val;
11 temp->left = temp->right = NULL;
12 return temp;
13}
14void inorder(struct node *root) {
15 if (root != NULL) {
16 inorder(root->left);
17 cout<<root->data<<" ";
18 inorder(root->right);
19 }
20}
21struct node* insertNode(struct node* node, int val) {
22 if (node == NULL) return createNode(val);
23 if (val < node->data)
24 node->left = insertNode(node->left, val);
25 else if (val > node->data)
26 node->right = insertNode(node->right, val);
27 return node;
28}
29int main() {
30 struct node *root = NULL;
31 root = insertNode(root, 4);
32 insertNode(root, 5);
33 insertNode(root, 2);
34 insertNode(root, 9);
35 insertNode(root, 1);
36 insertNode(root, 3);
37 cout<<"In-Order traversal of the Binary Search Tree is: ";
38 inorder(root);
39 return 0;
40}
1//The following code contains all the DFS traversal
2//I have first created a Binary search tree
3//Then performed DFS search :- 1.Inorder;2.Preorder;3.Postorder
4#include <iostream>
5
6using namespace std;
7struct node
8{
9 int data;
10 node* left;
11 node*right;
12};
13node* getnode(int value)
14{
15 node* temp=new node;
16 temp->data=value;
17 temp->left=NULL;
18 temp->right=NULL;
19 return temp;
20}
21node* insert_bst(node* roots,int value)
22{
23 if(roots==NULL)
24 {
25 return getnode(value);
26 }
27 if(roots->data>value)
28 {
29 roots->left=insert_bst(roots->left,value);
30 }
31 else if(roots->data<value)
32 {
33 roots->right=insert_bst(roots->right,value);
34 }
35 return roots;
36}
37void Inorder(node* roots)
38{
39 if(roots==NULL)
40 {
41 return;
42 }
43 else
44 {
45 Inorder(roots->left);
46 cout<<roots->data<<" ";
47 Inorder(roots->right);
48 }
49}
50void post_order(node* roots)
51{
52 if(roots==NULL)
53 {
54 return;
55 }
56 else
57 {
58 post_order(roots->left);
59 post_order(roots->right);
60 cout<<roots->data<<" ";
61 }
62}
63void preorder(node* root)
64{
65 if(root==NULL)
66 return;
67 cout<<root->data<<" ";
68 preorder(root->left);
69 preorder(root->right);
70}
71int main()
72{
73 node* root=new node;
74 root=NULL;
75 int number_of_nodes;
76 cin>>number_of_nodes;
77 int value;
78 for(int i=0;i<number_of_nodes;i++)
79 {
80 cin>>value;
81 root=insert_bst(root,value);
82 }
83 cout<<"Inorder Travesral:"<<endl;
84 Inorder(root);
85 cout<<endl;
86 cout<<"Postorder traversal:"<<endl;
87 post_order(root);
88 cout<<endl;
89 cout<<"preorder traversal:"<<endl;
90 preorder(root);
91 cout<<endl;
92 return 0;
93}
94