forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTreeInorderTraversal.java
54 lines (48 loc) · 1.47 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
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
public class BinaryTreeInorderTraversal {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new LinkedList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
while (!stack.isEmpty() || root != null) {
if (root != null) {
stack.push(root);
root = root.left;
} else {
root = stack.pop();
list.add(root.val);
root = root.right;
}
}
return list;
}
public List<Integer> inorderTraversal2(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}
List<Integer> res = new ArrayList<>();
TreeNode pre = null;
while (root != null) {
if (root.left == null) {
res.add(root.val);
root = root.right;
} else {
pre = root.left;
while (pre.right != null && pre.right != root) {
pre = pre.right;
}
if (pre.right == null) {
pre.right = root;
root = root.left;
} else {
pre.right = null;
res.add(root.val);
root = root.right;
}
}
}
return res;
}
}