-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program for creating and traversing a binary tree preorder, inorder, and postorder.cpp
80 lines (73 loc) · 1.76 KB
/
Program for creating and traversing a binary tree preorder, inorder, and postorder.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
#include <iostream>
using namespace std;
// node struct definition
struct Node {
int data;
Node* left;
Node* right;
};
// function to create a new node
Node* createNode(int data) {
Node* newNode = new Node;
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// function to insert a node into the binary tree
Node* insertNode(Node* root, int data) {
if (root == NULL) {
return createNode(data);
} else if (data <= root->data) {
root->left = insertNode(root->left, data);
} else {
root->right = insertNode(root->right, data);
}
return root;
}
// function for preorder traversal
void preorderTraversal(Node* root) {
if (root == NULL) {
return;
}
cout << root->data << " ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}
// function for inorder traversal
void inorderTraversal(Node* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
cout << root->data << " ";
inorderTraversal(root->right);
}
// function for postorder traversal
void postorderTraversal(Node* root) {
if (root == NULL) {
return;
}
postorderTraversal(root->left);
postorderTraversal(root->right);
cout << root->data << " ";
}
int main() {
Node* root = NULL;
root = insertNode(root, 10);
insertNode(root, 8);
insertNode(root, 15);
insertNode(root, 6);
insertNode(root, 9);
insertNode(root, 13);
insertNode(root, 18);
cout << "Preorder traversal: ";
preorderTraversal(root);
cout << endl;
cout << "Inorder traversal: ";
inorderTraversal(root);
cout << endl;
cout << "Postorder traversal: ";
postorderTraversal(root);
cout << endl;
return 0;
}