-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiterative_inorder1.cpp
104 lines (85 loc) · 1.96 KB
/
iterative_inorder1.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
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <stack>
using namespace std;
/* A binary tree node has data, left child and right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* Helper function that allocates a new node with the given data and
NULL left and right pointers.*/
struct node* newNode(int data)
{
struct node* node = new struct node;
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
// An iterative process to print preorder traversal of Binary tree
void iterativePreorder(node *root)
{
stack<node*>st;
st.push(root);
while(!st.empty()){
node* node = st.top();
cout<<node->data<<" ";
st.pop();
if(node->right)
st.push(node->right);
if(node->left)
st.push(node->left);
}
}
// iterative inorder LDR
void iterativeInorder(node* root){
stack<node*> st;
while(1){
while(root){
st.push(root);
root=root->left;
}
if(st.empty())
break;
root=st.top(); st.pop();
cout<<root->data<<" ";
root=root->right;
}
}
//LDR
void inorder(node* root){
if(root){
inorder(root->left); // L
cout<<root->data<<" "; // D
inorder(root->right); // R
}
}
// Driver program to test above functions
int main()
{
/* Constructed binary tree is
10
/ \
8 2
/ \ /
3 5 2
*/
struct node *root = newNode(10);
root->left = newNode(8);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(5);
root->right->left = newNode(2);
cout<<"\n----Iterative Preorder Traversal-----"<<endl;
iterativePreorder(root);
cout<<"\n\n---Inorder Traversal --- \n"<<endl;
inorder(root);
cout<<"\n\n-----Iterative Inorder--\n\n";
iterativeInorder(root);
cout<<endl;
return 0;
}