Iterative solution in Java, 1ms


  • 0
    public List<Integer> inorderTraversal(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<TreeNode> stack = new Stack();
        stack.add(root);
        while (!stack.empty()) {
            TreeNode peek = stack.peek();
            if (peek.left != null) {
                stack.add(peek.left);
                peek.left = null;
            } else {
                stack.pop();
                list.add(peek.val);
                if (peek.right != null) {
                    stack.add(peek.right);
                }
            }
        }
        return list;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.