-
Notifications
You must be signed in to change notification settings - Fork 156
/
Inorder_Traversal.cpp
123 lines (99 loc) · 3.11 KB
/
Inorder_Traversal.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/*Traversal in Binary Tree
Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways.
One way of traversing is Depth First Search:
1
/ \
2 3
/ \
4 5
(a) Inorder (Left, Root, Right) : 4 2 5 1 3
(b) Preorder (Root, Left, Right) : 1 2 4 5 3
(c) Postorder (Left, Right, Root) : 4 5 2 3 1
Inorder Traversal :
Algorithm Inorder(tree) :
1. Traverse the left subtree, i.e., call Inorder(left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right-subtree)
Uses of Inorder :
In case of binary search trees (BST), Inorder traversal gives nodes in increasing order.
Here we discussed both approahes i.e iterative & recursive:
*/
//Iterative approach:
#include <bits/stdc++.h>
using namespace std;
// Data structure to store a binary tree node
struct Node
{
int data;
Node *left, *right;
Node(int data)
{
this->data = data;
this->left = this->right = nullptr;
}
};
// Recursive function to perform inorder traversal on the tree
void inorderRecursion(Node* root)
{
// return if the current node is empty
if (root == nullptr) {
return;
}
// Traverse the left subtree
inorderRecursion(root->left);
// Display the data part of the root (or current node)
cout << root->data << " ";
// Traverse the right subtree
inorderRecursion(root->right);
}
void inorderIterative(Node* root)
{
// create an empty stack
stack<Node*> stack;
// start from the root node (set current node to the root node)
Node* curr = root;
// if the current node is null and the stack is also empty, we are done
while (!stack.empty() || curr != nullptr)
{
// if the current node exists, push it into the stack (defer it)
// and move to its left child
if (curr != nullptr)
{
stack.push(curr);
curr = curr->left;
}
else {
// otherwise, if the current node is null, pop an element from the stack,
// print it, and finally set the current node to its right child
curr = stack.top();
stack.pop();
cout << curr->data << " ";
curr = curr->right;
}
}
}
int main()
{
/* Construct the following tree
1
/ \
/ \
2 3
/ / \
/ / \
4 5 6
/ \
/ \
7 8
*/
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->right->left = new Node(5);
root->right->right = new Node(6);
root->right->left->left = new Node(7);
root->right->left->right = new Node(8);
inorderRecursion(root);
return 0;
}