-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInOrder.java
More file actions
38 lines (35 loc) · 992 Bytes
/
InOrder.java
File metadata and controls
38 lines (35 loc) · 992 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
30
31
32
33
34
35
36
37
38
import java.util.*;
public class InOrder {
public void traversal(TreeNode root, List<Integer> res) {
if (root == null) {
return;
}
traversal(root.left, res);
res.add(root.val);
traversal(root.right, res);
}
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
traversal(root, res);
return res;
}
public List<Integer> inorder(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode curr = root;
while (true) {
if (curr != null) {
stack.push(curr);
curr = curr.left;
} else {
if (stack.isEmpty()) {
break;
}
curr = stack.pop();
res.add(curr.val);
curr = curr.right;
}
}
return res;
}
}