-
Notifications
You must be signed in to change notification settings - Fork 577
Expand file tree
/
Copy pathImplement Inorder Traversal Algorithm
More file actions
65 lines (57 loc) · 1.75 KB
/
Implement Inorder Traversal Algorithm
File metadata and controls
65 lines (57 loc) · 1.75 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
61
62
63
64
65
#include <stdio.h>
#include <stdlib.h>
// Define a structure for binary tree node
struct Node {
int data;
struct Node *left, *right;
};
// Function to create a new node
struct Node* newNode(int data) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL;
return node;
}
// Function to perform Morris Inorder Traversal
void morrisInorderTraversal(struct Node* root) {
struct Node* current = root;
struct Node* predecessor;
printf("Inorder traversal using Morris algorithm:\n");
while (current != NULL) {
if (current->left == NULL) {
// No left child — print and move right
printf("%d ", current->data);
current = current->right;
} else {
// Find inorder predecessor
predecessor = current->left;
while (predecessor->right != NULL && predecessor->right != current)
predecessor = predecessor->right;
// Make thread or remove it
if (predecessor->right == NULL) {
predecessor->right = current;
current = current->left;
} else {
predecessor->right = NULL;
printf("%d ", current->data);
current = current->right;
}
}
}
printf("\n");
}
// Helper to build a sample binary tree for testing
// Level order: 1 2 3 4 5
struct Node* buildSampleTree() {
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
return root;
}
int main() {
struct Node* root = buildSampleTree();
morrisInorderTraversal(root);
return 0;
}