[leetcode] problem 94 – binary tree inorder traversal

Given a binary tree, return the inorder traversal of its nodes’ values.

Example

Input: [1,null,2,3]

1
2
3
4
5
1

2
/
3

Output: [1,3,2]

Follow up

Recursive solution is trivial, could you do it iteratively?

Code

1
2
3
4
5
6
public class  {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;

while (current != null || !stack.isEmpty()) {
while (current != null) {
stack.push(current);
current = current.left;
}

TreeNode node = stack.pop();
result.add(node.val);
current = node.right;
}

return result;
}