TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
morrisinorder.cpp
1
#include <iostream>
2
#include <queue>
3
4
/**************************
5
@author shrutisheoran
6
**************************/
7
8
using namespace
std;
9
10
struct
Btree
{
11
int
data;
12
struct
Btree
*left;
// Pointer to left subtree
13
struct
Btree
*right;
// Pointer to right subtree
14
};
15
16
void
insert
(
Btree
**root,
int
d) {
17
Btree
*nn =
new
Btree
();
// Creating new node
18
nn->data = d;
19
nn->left = NULL;
20
nn->right = NULL;
21
if
(*root == NULL) {
22
*root = nn;
23
return
;
24
}
else
{
25
queue<Btree *> q;
26
// Adding root node to queue
27
q.push(*root);
28
while
(!q.empty()) {
29
Btree
*
node
= q.front();
30
// Removing parent node from queue
31
q.pop();
32
if
(
node
->left)
33
// Adding left child of removed node to queue
34
q.push(
node
->left);
35
else
{
36
// Adding new node if no left child is present
37
node
->left = nn;
38
return
;
39
}
40
if
(
node
->right)
41
// Adding right child of removed node to queue
42
q.push(
node
->right);
43
else
{
44
// Adding new node if no right child is present
45
node
->right = nn;
46
return
;
47
}
48
}
49
}
50
}
51
52
void
morrisInorder(
Btree
*root) {
53
Btree
*curr = root;
54
Btree
*temp;
55
while
(curr) {
56
if
(curr->left == NULL) {
57
cout << curr->data <<
" "
;
58
// If left of current node is NULL then curr is shifted to right
59
curr = curr->right;
60
}
else
{
61
// Left of current node is stored in temp
62
temp = curr->left;
63
// Moving to extreme right of temp
64
while
(temp->right && temp->right != curr) temp = temp->right;
65
// If extreme right is null it is made to point to currrent node
66
// (will be used for backtracking)
67
if
(temp->right == NULL) {
68
temp->right = curr;
69
// current node is made to point its left subtree
70
curr = curr->left;
71
}
72
// If extreme right already points to currrent node it it set to
73
// null
74
else
if
(temp->right == curr) {
75
cout << curr->data <<
" "
;
76
temp->right = NULL;
77
// current node is made to point its right subtree
78
curr = curr->right;
79
}
80
}
81
}
82
}
83
84
void
deleteAll(
const
Btree
*
const
root) {
85
if
(root) {
86
deleteAll(root->left);
87
deleteAll(root->right);
88
delete
root;
89
}
90
}
91
92
int
main
() {
93
// Testing morrisInorder funtion
94
Btree
*root = NULL;
95
int
i;
96
for
(i = 1; i <= 7; i++)
insert
(&root, i);
97
cout <<
"Morris Inorder: "
;
98
morrisInorder(root);
99
deleteAll(root);
100
return
0;
101
}
insert
node * insert(node *root, int item)
inserts a new element into AVL tree
Definition
avltree.cpp:92
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
Btree
Definition
morrisinorder.cpp:10
node
Definition
binary_search_tree.cpp:11
data_structures
morrisinorder.cpp
Generated by
1.12.0