-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrees.cpp
104 lines (77 loc) · 1.86 KB
/
Trees.cpp
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int val) {
data = val;
left = right = NULL;
}
};
void printInorder(Node* root) {
if (root == NULL) return;
printInorder(root->left);
cout << root->data << " ";
printInorder(root->right);
}
void printPostorder(Node* root) {
if (root == NULL) return;
printPostorder(root->left);
printPostorder(root->right);
cout << root->data << " ";
}
void printPreorder(Node* root) {
if (root == NULL) return;
cout << root->data << " ";
printPreorder(root->left);
printPreorder(root->right);
}
int height(Node* node) {
if (node == NULL)
return 0;
else {
int lHeight = height(node->left);
int rHeight = height(node->right);
return 1 + max(lHeight,rHeight);
}
}
void printGivenLevel(Node*root,int level){
if(root == NULL) return;
if(level == 1){
cout<<root->data<<" ";
} else if(level > 1){
printGivenLevel(root->left,level-1);
printGivenLevel(root->right,level-1);
}
}
void printLevelOrder(Node* root) {
int h = height(root);
for (int i = 1; i <= h; i++) {
printGivenLevel(root, i);
}
}
int main() {
Node* root = new Node(10);
root->left = new Node(20);
root->right = new Node(30);
root->left->left = new Node(40);
root->left->right = new Node(50);
root->right->left = new Node(60);
root->right->right = new Node(70);
cout << "Inorder Traversal: ";
printInorder(root);
cout << endl;
cout << "Postorder Traversal: ";
printPostorder(root);
cout << endl;
cout << "Preorder Traversal: ";
printPreorder(root);
cout << endl;
cout << "Levelorder Traversal: ";
printLevelOrder(root);
cout << endl;
return 0;
}