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