-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMorisPreOrder.cpp
More file actions
60 lines (57 loc) · 1.51 KB
/
MorisPreOrder.cpp
File metadata and controls
60 lines (57 loc) · 1.51 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
#include<bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node*left;
Node*right;
};
Node* root = NULL;
struct Node* insert(struct Node* root, int x) {
struct Node* temp = (struct Node*)malloc(sizeof(struct Node*));
temp->data = x;
temp->left = NULL;
temp->right = NULL;
if(root == NULL) {
root = temp;
}
else if(x <= root->data) {
root->left = insert(root->left, x);
} else {
root->right = insert(root->right, x);
}
return root;
}
void MorrisPreOrder (Node* root) {
struct Node* current = root;
while(current != NULL) {
if(current->left == NULL) {
cout<<current->data<<endl;
current = current->right;
} else {
struct Node* predecessor = current->left;
while(predecessor->right!=current && predecessor->right!=NULL) {
predecessor = predecessor->right;
}
if(predecessor->right == NULL) {
predecessor->right = current;
cout<<current->data<<endl;
current=current->left;
} else {
predecessor->right = NULL;
current = current->right;
}
}
}
}
int main() {
root = insert(root,10);
root = insert(root,5);
root = insert(root,30);
root = insert(root,-2);
root = insert(root,6);
root = insert(root,2);
root = insert(root,-1);
root = insert(root,8);
root = insert(root,40);
MorrisPreOrder(root);
}