Is my Java solution right?


  • 0
    Q

    public class Solution {

    public List<Integer> preorderTraversal(TreeNode root)

    {

    List<Integer> ans = new ArrayList();

    if (root==null)

    return ans;

    if(root.val!=0)

    ans.add(root.val);

    if(root.left!=null)

    ans.addAll(preorderTraversal(root.left));

    if(root.right!=null)

    ans.addAll(preorderTraversal(root.right));

    return ans;
    }
    }

    I'm a chinese rookie and my solution is accepted but I found the answer by others is quite complex,I wondered did I under concerned about something?


  • 0

    Please format your code.
    And a link to such a "quite complex" solution would be good, so we know what you're talking about.

    To answer your question: Your solution is (almost) correct, but it's also very slow. Think of a deep tree where each inner node only has one child. The deepest nodes get copied over and over and over again and you have quadratic runtime rather than the easily possible linear runtime.

    Edit: I added the "(almost)" because you omit zeroes with your if(root.val!=0). No idea why you do it, but it's wrong. And the reason I didn't see it earlier is your missing formatting, making the code hard to read/follow. Please format your code.


Log in to reply
 

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