-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInorder_Iterator_of_a_tree.cpp
More file actions
129 lines (116 loc) · 2.17 KB
/
Inorder_Iterator_of_a_tree.cpp
File metadata and controls
129 lines (116 loc) · 2.17 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
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
124
125
126
127
128
129
#include <bits/stdc++.h>
using namespace std;
/*
* Node class definition for your reference.
* Do not modify this class or your code may not work.
*/
class Node
{
public:
int data;
Node *left;
Node *right;
Node(int d)
{
data = d;
left = right = NULL;
}
};
class TreeIterator
{
public:
Node *iter = NULL;
Node *flatten(Node *root)
{
if (!root)
return root;
if (!root->left and !root->right)
return root;
Node *ll = NULL;
Node *l = flatten(root->left);
Node *r = flatten(root->right);
if (!l and r)
{
root->right = r;
root->left = NULL;
ll = root;
}
else if (l and !r)
{
ll = l;
Node *t = ll;
while (t->right != NULL)
t = t->right;
root->left = NULL;
t->right = root;
}
else
{
ll = l;
Node *t = ll;
while (t->right != NULL)
t = t->right;
t->right = root;
root->left = NULL;
root->right = r;
}
return ll;
}
TreeIterator(Node *root)
{
iter = flatten(root);
}
/** @return the next smallest number */
int next()
{
int t = iter->data;
iter = iter->right;
return t;
}
/** @return whether we have a next smallest number */
bool hasNext()
{
return iter;
}
};
/*
*
*
* You do not need to refer or modify any code below this.
* Only modify the TreeIterator class definition.
*
*
*/
Node *buildTree()
{
int d;
cin >> d;
if (d == -1)
{
return NULL;
}
Node *root = new Node(d);
root->left = buildTree();
root->right = buildTree();
return root;
}
int main()
{
Node *root = buildTree();
TreeIterator t(root);
int c = 0;
while (t.hasNext())
{
if (c / 10 % 2 == 1)
{
cout << t.hasNext() << " ";
}
if (c % 7 == 0)
{
cout << "^ ";
}
cout << t.next() << " ";
c++;
}
return 0;
}