-
Notifications
You must be signed in to change notification settings - Fork 0
/
Traverse.java
39 lines (37 loc) · 1.01 KB
/
Traverse.java
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
public class Traverse {
static class Node{
int val;
Node left;
Node right;
Node(int v) {
val = v;
}
}
public void preOrderIter(Node root) {
if (root == null) return;
Deque<Node> td = new ArrayDeque<>();
td.push(root);
while (!td.isEmpty()) {
Node w = td.pop();
System.out.println(w);
if (w.left != null) td.push(w.left);
if (w.right != null) td.push(w.right);
}
}
public void postOrderIter(Node root) {
if (root == null) return;
Deque<Node> wd = new ArrayDeque<>();
Deque<Node> res = new ArrayDeque<>();
wd.push(root);
while (!wd.isEmpty()) {
Node w = wd.pop();
res.push(w);
if (w.right != null) wd.push(w.right);
if (w.left != null) wd.push(w.left);
}
while (!res.isEmpty() {
Node n = res.pop();
System.out.println(n.val);
}
}
}