binary tree inorder traversal


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

For example:
Given binary tree [1,null,2,3],

1
2
3
4
5
1
2
/
3

return [1,3,2].

Note: 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
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
inOrder(res, root);
return res;
}
public void inOrder(List<Integer> res, TreeNode node) {
if(node != null) {
inOrder(res,node.left);
res.add(node.val);
inOrder(res,node.right);
}
}
}