-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path0066. Binary Tree Preorder Traversal.java
More file actions
56 lines (51 loc) · 1.55 KB
/
0066. Binary Tree Preorder Traversal.java
File metadata and controls
56 lines (51 loc) · 1.55 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
public class Solution {
/**
* @param root: A Tree
* @return: Preorder in ArrayList which contains node values.
*/
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
if(root == null) return result;
Stack<TreeNode> nodes = new Stack<>(); //LIFO
nodes.push(root);
while(!nodes.isEmpty()){
TreeNode curr = nodes.pop();
result.add(curr.val);
if(curr.right != null){ //must push right on first so that left is accessed first
nodes.push(curr.right);
}
if(curr.left != null){
nodes.push(curr.left);
}
}
return result;
}
}
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution { //with recursion
/**
* @param root: A Tree
* @return: Preorder in ArrayList which contains node values.
*/
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
if(root == null) return result;
helper(root, result);
return result;
}
public void helper(TreeNode curr, List<Integer> result){
result.add(curr.val);
if(curr.left != null) helper(curr.left, result); //left before right
if(curr.right != null) helper(curr.right, result);
}
}