-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path94.java
52 lines (49 loc) · 1.38 KB
/
94.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// recursion
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
helper(root, res);
return res;
}
public void helper(TreeNode root, List<Integer> res) {
if (root != null) {
if (root.left != null){
helper(root.left, res);
}
res.add(root.val);
if (root.right != null){
helper(root.right, res);
}
}
}
}
// stack
// 指针curr
// while左边一直有值或curr指向一个non-null node,stack push 每一个值, 左边到底后,指针从stack顶端开始pop, pop完之后res加入current值,指针往
// current.right指
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
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;
}
}