forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
postorder.cpp
70 lines (61 loc) · 1.48 KB
/
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
#include<iostream>
using namespace std;
//creating structure for node
struct Node {
char data;
struct Node *left;
struct Node *right;
};
// Insert Function
Node* Insert(Node *root, char data) {
//if root have no value
//then create a node and insert values
if (root == NULL) {
root = new Node();
root->data = data;
root->left = root->right = NULL;
}
//check if data is less than root value
//then insert into left subtree
else if (data <= root->data)
root->left = Insert(root->left, data);
//check if data is less than root value
//then insert into right subtree
else
root->right = Insert(root->right, data);
return root;
}
//Postorder Function
void Postorder(Node *root) {
if (root == NULL) return;
// if tree is empty then return
//visit left and right subtree
Postorder(root->left);
Postorder(root->right);
//otherwise print data
printf("%c ", root->data);
}
//Main Function began
int main() {
Node* root = NULL;
//input values
root = Insert(root, 'M');
root = Insert(root, 'B');
root = Insert(root, 'Q');
root = Insert(root, 'Z');
root = Insert(root, 'A');
root = Insert(root, 'C');
//Print Nodes in Preorder.
cout << "\tOUTPUT\n";
cout << "Postorder traversal : ";
Postorder(root);
cout << "\n";
}
//Main Ends
/*
Sample Input Output:
Input -> M B Q Z A C
OUTPUT:
Postorder traversal : A C B Z Q M
Time Complexity: O(n)
*/