-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathSolution094.java
73 lines (58 loc) · 1.41 KB
/
Solution094.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
62
63
64
65
66
67
68
69
70
71
72
73
package algorithm.leetcode;
import java.util.LinkedList;
import java.util.List;
/**
* @author: mayuan
* @desc: 二叉树的中序遍历
* @date: 2019/03/05
*/
public class Solution094 {
/**
* 非递归中序遍历二叉树
*
* @param root
* @return
*/
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ans = new LinkedList<>();
if (null == root) {
return ans;
}
LinkedList<TreeNode> stack = new LinkedList<>();
TreeNode cur = root;
while (null != cur || !stack.isEmpty()) {
while (null != cur) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
ans.add(cur.val);
cur = cur.right;
}
return ans;
}
public List<Integer> inorderTraversal2(TreeNode root) {
List<Integer> ans = new LinkedList<>();
if (null == root) {
return ans;
}
dfs(ans, root);
return ans;
}
public void dfs(List<Integer> answer, TreeNode node) {
if (null == node) {
return;
}
dfs(answer, node.left);
answer.add(node.val);
dfs(answer, node.right);
}
private class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}