-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeInorderTraversal.java
More file actions
54 lines (45 loc) · 1.35 KB
/
BinaryTreeInorderTraversal.java
File metadata and controls
54 lines (45 loc) · 1.35 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
43
44
45
46
47
48
49
50
51
52
53
54
package leetcode;
import utils.TreeNode;
import utils.Trees;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
/**
* BinaryTreeInorderTraversal
* https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
*
* @since 2020-09-14
*/
public class BinaryTreeInorderTraversal {
public static void main(String[] args) {
TreeNode head = Trees.fromIntegers(new Integer[]{1, null, 2, 3});
BinaryTreeInorderTraversal sol = new BinaryTreeInorderTraversal();
List<Integer> res = sol.inorderTraversal(head);
for (Integer value : res) {
System.out.println(value);
}
}
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>(); // 刷题一般不返回null
if (root == null) {
return res;
}
Stack<TreeNode> next = new Stack<>();
next.add(root);
TreeNode currLeft = root.left;
while (currLeft != null) {
next.add(currLeft);
currLeft = currLeft.left;
}
while (!next.isEmpty()) {
TreeNode curr = next.pop();
res.add(curr.val);
TreeNode toAdd = curr.right;
while (toAdd != null) {
next.add(toAdd);
toAdd = toAdd.left;
}
}
return res;
}
}