-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtree-DFS-recursion.cpp
More file actions
executable file
·70 lines (62 loc) · 1.32 KB
/
tree-DFS-recursion.cpp
File metadata and controls
executable file
·70 lines (62 loc) · 1.32 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
64
65
66
67
68
69
70
/* Function to perform PRE, IN, POST or depth-first traversal of tree using recursion. */
#include <iostream>
#include <cstdio>
using namespace std;
class node
{
public:
int data;
node* left;
node* right;
node(int data) {
this->data = data;
left = right = NULL;
}
};
node* createBinaryTree(node* root, int depth, int value) {
if (depth < 1)
return NULL;
root = new node(value);
root->left = createBinaryTree(root->left, depth-1, value*2);
root->right = createBinaryTree(root->right, depth-1, value*2+1);
return root;
}
void preorder(node* root) {
if (!root)
return;
cout<<root -> data<<" ";
preorder(root->left);
preorder(root->right);
return;
}
void inorder(node* root) {
if (!root)
return;
inorder(root->left);
cout<<root -> data<<" ";
inorder(root->right);
return;
}
void postorder(node* root) {
if (!root)
return;
postorder(root->left);
postorder(root->right);
cout<<root -> data<<" ";
return;
}
int main() {
freopen("input.txt","r",stdin);
int depth;
cin>>depth;
node* root;
root = createBinaryTree(root, depth, 1);
cout<<"Preorder traversal : ";
preorder(root);
cout<<endl<<"Inorder traversal : ";
inorder(root);
cout<<endl<<"Postorder traversal : ";
postorder(root);
cout<<endl;
return 0;
}