-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBinary_144.java
More file actions
42 lines (40 loc) · 1.15 KB
/
Binary_144.java
File metadata and controls
42 lines (40 loc) · 1.15 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
import java.util.*;
public class Binary_144 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
if (root != null)
stack.push(root);
while(!stack.isEmpty()) {
TreeNode p = stack.pop();
result.add(p.val);
if (p.right != null)
stack.push(p.right);
if (p.left != null)
stack.push(p.left);
}
return result;
// Post Order Traverse
/*
LinkedList<Integer> result = new LinkedList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
if (root != null)
stack.push(root);
while(!stack.isEmpty()) {
TreeNode p = stack.pop();
result.addFirst(p.val);
if (p.left != null)
stack.push(p.left);
if (p.right != null)
stack.push(p.right);
}
return result;
*/
}
}