The other method is wrong answer, can you tell me?


  • 0
    S
    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        private List list=new ArrayList();
        public List<Integer> preorderTraversal(TreeNode root) {
            if(root==null) return list;
            list.add(root.val);  // if(root!=null) list.add(root.val);
            if(root.left!=null)
                preorderTraversal(root.left);
            if(root.right!=null)
                preorderTraversal(root.right);
            return list;
        }
    }

Log in to reply
 

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