-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpreorderTraversal.java
More file actions
29 lines (28 loc) · 915 Bytes
/
preorderTraversal.java
File metadata and controls
29 lines (28 loc) · 915 Bytes
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
// recursive
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
if (root != null){
result.add(root.val);
result.addAll(preorderTraversal(root.left));
result.addAll(preorderTraversal(root.right));
}
return result;
}
}
// iterative
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
if (root == null) return result;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.isEmpty()){
TreeNode node = stack.pop();
result.add(node.val);
if (node.right != null) stack.push(node.right);
if (node.left != null) stack.push(node.left);
}
return result;
}
}