-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathBinaryTreeInorderTraversal.java
61 lines (47 loc) · 1.45 KB
/
BinaryTreeInorderTraversal.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package leetcode.solution.tree.traversal;
import leetcode.structure.TreeNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* 94. Binary Tree Inorder Traversal
*/
public class BinaryTreeInorderTraversal {
public static void main(String[] args) {
Integer[] pArray = {1, 4, 2, 3, 5, 6, 7};
TreeNode p = TreeNode.constructTree(pArray);
System.out.println(inorderTraversal(p));
System.out.println(inorderIterator(p));
}
public static List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
helper(root, result);
return result;
}
private static void helper(TreeNode root, List<Integer> result) {
if (root == null) {
return;
}
helper(root.left, result);
result.add(root.val);
helper(root.right, result);
}
public static List<Integer> inorderIterator(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode curr = root;
while (curr != null || !stack.isEmpty()) {
while (curr != null) {
stack.push(curr);
curr = curr.left;
}
curr = stack.pop();
res.add(curr.val);
curr = curr.right;
}
return res;
}
}