Skip to content

Commit a05f3b5

Browse files
MEDIUM/src/medium/BinaryTreePreorderTraversal.java
1 parent 02db10e commit a05f3b5

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
}

0 commit comments

Comments
 (0)