Given a binary tree, return the inorder traversal of its nodes’ values.
Example:
1
2
3
4
5
6
7
8
| Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
|
Follow up: Recursive solution is trivial, could you do it iteratively?
Solution:
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
| /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private List<Integer> list = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if (root == null) {
return Collections.emptyList();
}
Stack<TreeNode> q = new Stack<>();
TreeNode curr = root;
while (!q.isEmpty() || curr != null) {
while (curr != null) {
q.push(curr);
curr = curr.left;
}
curr = q.pop();
list.add(curr.val);
curr = curr.right;
}
return list;
}
public List<Integer> inorderTraversal2(TreeNode root) {
if (root == null) {
return Collections.emptyList();
}
inorderTraversal(root.left);
list.add(root.val);
inorderTraversal(root.right);
return list;
}
}
|