My 2ms java recursive solution (7 lines)


  • 1
    B
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        if (root!=null) {
            list.add(root.val);
            list.addAll(preorderTraversal(root.left));
            list.addAll(preorderTraversal(root.right));
        }
        return list;
    }

  • 0
    L

    Note: Recursive solution is trivial, could you do it iteratively?
    You should solve it iteratively :)


Log in to reply
 

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