-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_tree_trversal.cpp
More file actions
63 lines (62 loc) · 1.2 KB
/
binary_tree_trversal.cpp
File metadata and controls
63 lines (62 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include<iostream>
using namespace std;
struct tree //structure to define node of tree
{
int data;
tree* left;
tree* right;
};
tree* insert(int val) //insertion in the tree
{
tree* newnode=new tree();
newnode->data=val;
newnode->left=NULL;
newnode->right=NULL;
return newnode;
}
//inorder traversal of tree
void inorder_traversal(tree* root)
{
//if root is null then return
if(root==NULL)
return;
inorder_traversal(root->left);
cout<<root->data<<"\t";
inorder_traversal(root->right);
}
//preorder traversal of tree
void preorder_traversal(tree* root)
{
if(root==NULL)
return;
cout<<root->data<<"\t";
preorder_traversal(root->left);
preorder_traversal(root->right);
}
//postorder traversal of tree
void postorder_traversal(tree* root)
{
if(root==NULL)
return;
preorder_traversal(root->left);
preorder_traversal(root->right);
cout<<root->data<<"\t";
}
int main()
{
tree* root;
root=insert(1);
root->left=insert(2);
root->right=insert(3);
root->left->left=insert(4);
cout<<"Inorder traversal-\n";
inorder_traversal(root);
cout<<endl;
cout<<"Preorder traversal-\n";
preorder_traversal(root);
cout<<endl;
cout<<"Postorder traversal-\n";
postorder_traversal(root);
cout<<endl;
return 0;
}