1
1
package com .baeldung .algorithms .dfs ;
2
2
3
- import java .util .LinkedList ;
4
- import java .util .Queue ;
5
3
import java .util .Stack ;
6
4
7
5
public class BinaryTree {
@@ -124,69 +122,43 @@ public void traversePostOrder(Node node) {
124
122
}
125
123
}
126
124
127
- public void traverseLevelOrder () {
128
- if (root == null ) {
129
- return ;
130
- }
131
-
132
- Queue <Node > nodes = new LinkedList <>();
133
- nodes .add (root );
134
-
135
- while (!nodes .isEmpty ()) {
136
-
137
- Node node = nodes .remove ();
138
125
139
- System .out .print (" " + node .value );
140
-
141
- if (node .left != null ) {
142
- nodes .add (node .left );
143
- }
144
-
145
- if (node .left != null ) {
146
- nodes .add (node .right );
147
- }
148
- }
149
- }
150
-
151
-
152
126
public void traverseInOrderWithoutRecursion () {
153
- Stack <Node > stack = new Stack <Node >();
127
+ Stack <Node > stack = new Stack <>();
154
128
Node current = root ;
155
- stack .push (root );
156
- while (! stack .isEmpty ()) {
157
- while (current .left != null ) {
158
- current = current .left ;
159
- stack .push (current );
160
- }
161
- current = stack .pop ();
162
- visit (current .value );
163
- if (current .right != null ) {
164
- current = current .right ;
129
+
130
+ while (current != null || !stack .isEmpty ()) {
131
+ while (current != null ) {
165
132
stack .push (current );
133
+ current = current .left ;
166
134
}
135
+
136
+ Node top = stack .pop ();
137
+ visit (top .value );
138
+ current = top .right ;
167
139
}
168
140
}
169
-
141
+
170
142
public void traversePreOrderWithoutRecursion () {
171
- Stack <Node > stack = new Stack <Node >();
172
- Node current = root ;
143
+ Stack <Node > stack = new Stack <>();
144
+ Node current ;
173
145
stack .push (root );
174
146
while (! stack .isEmpty ()) {
175
147
current = stack .pop ();
176
148
visit (current .value );
177
-
149
+
178
150
if (current .right != null )
179
151
stack .push (current .right );
180
-
152
+
181
153
if (current .left != null )
182
154
stack .push (current .left );
183
- }
155
+ }
184
156
}
185
-
157
+
186
158
public void traversePostOrderWithoutRecursion () {
187
- Stack <Node > stack = new Stack <Node >();
159
+ Stack <Node > stack = new Stack <>();
188
160
Node prev = root ;
189
- Node current = root ;
161
+ Node current ;
190
162
stack .push (root );
191
163
192
164
while (!stack .isEmpty ()) {
@@ -206,14 +178,14 @@ public void traversePostOrderWithoutRecursion() {
206
178
stack .push (current .left );
207
179
}
208
180
}
209
- }
210
- }
211
-
181
+ }
182
+ }
183
+
212
184
private void visit (int value ) {
213
- System .out .print (" " + value );
185
+ System .out .print (" " + value );
214
186
}
215
-
216
- class Node {
187
+
188
+ static class Node {
217
189
int value ;
218
190
Node left ;
219
191
Node right ;
0 commit comments