LeetCode

Binary Tree Inorder Traversal

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].

Java

public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> rst = new ArrayList<Integer>();

        if(root == null) {
            return rst;
        }

        Stack<TreeNode> stack = new Stack<TreeNode>();
        while(!stack.empty() || root != null) {
            if(root != null) {
                stack.push(root);
                root = root.left;
            } else {
                root = stack.pop();
                rst.add(root.val);
                root = root.right;
            }
        }
        return rst;
    }
}