File tree Expand file tree Collapse file tree 1 file changed +17
-1
lines changed Expand file tree Collapse file tree 1 file changed +17
-1
lines changed Original file line number Diff line number Diff line change 7
7
import classes .TreeNode ;
8
8
9
9
public class BinaryTreePreorderTraversal {
10
- public List <Integer > preorderTraversal_iterative (TreeNode root ) {
10
+ public List <Integer > preorderTraversal_iterative_original (TreeNode root ) {
11
11
List <Integer > list = new ArrayList ();
12
12
Stack <TreeNode > stack = new Stack ();
13
13
if (root == null ) return list ;
@@ -21,6 +21,22 @@ public List<Integer> preorderTraversal_iterative(TreeNode root) {
21
21
return list ;
22
22
}
23
23
24
+ public List <Integer > preorderTraversal_iterative_online (TreeNode root ) {
25
+ List <Integer > list = new ArrayList ();
26
+ Stack <TreeNode > stack = new Stack ();
27
+ if (root == null ) return list ;
28
+ while (root != null || !stack .isEmpty ()){
29
+ if (root != null ){
30
+ list .add (root .val );
31
+ stack .push (root );
32
+ root = root .left ;
33
+ } else {
34
+ root = stack .pop ().right ;
35
+ }
36
+ }
37
+ return list ;
38
+ }
39
+
24
40
//recursive solution is really trivial:
25
41
public List <Integer > preorderTraversal_recursive (TreeNode root ) {
26
42
List <Integer > list = new ArrayList ();
You can’t perform that action at this time.
0 commit comments