Given a binary tree, return the inorder traversal of its nodes' values.
For example: Given binary tree {1,#,2,3},
1 \ 2 / 3
return [1,3,2].
The idea is push to stack the element until you find the leftmost node, then pop stack, and do the same thing in the right sub tree.
//LMR
public List<Integer> inorderTraversal(TreeNode root) {
//incoming node is root
Stack<TreeNode> nodes = new Stack<TreeNode>();
List<Integer> values = new ArrayList<Integer>();
while (!nodes.isEmpty() || root!=null) {
if (root != null) {
nodes.push(root);
root = root.left;
} else {
root = nodes.pop();
values.add(root.val);
root = root.right;
}
}
return values;
}