Problem in using javascript to code the preorder traversal


  • 0
    W
    var preorderTraversal = function(root) {
        var array = [];
        if(!(root == null)){
           array.push(root.val) ;
            preorderTraversal(root.left);
            preorderTraversal(root.right);
        }
        return array;
    };
    

    The code failed in testing when the test case is [1,2], I only output [1], how to fix it?


  • 0
    I

    @Weidong_Diao
    Hi there, I have a similar but slightly different issue. Here is my code.

    var res = [];
    var preorderTraversal = function(root) {
        if(root !== null){
            res.push(root.val); 
            preorderTraversal(root.left);
            preorderTraversal(root.right);
        }
        return res;
    };
    

    My code also failed in testing when the test case is [1,2], but I output [1,1,2]. Do you get to fix your code?


  • 0
    I

    I think it is a bug. My code actually works when I use the custom test case function provided by the website.


  • 0
    L

    @injune1123
    Hey I've got the same problem. I think it just saved all text cases results in the array res if we initiated outside the function perorderTraversal.

    You can try to create res inside the function perorderTraversal.


Log in to reply
 

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