Javascript root->left->right using stack, easy understanding


  • 0

    My solution is first looking for the left most node, at the same time push node.val into result. Until finding a null node, go to the right node.

    var preorderTraversal = function(root) {
        if (root === null) 
            return [];
        var result = [], stack = [];
        while(root != null || stack.length != 0){
            while(root != null){
                result.push(root.val);
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            root = root.right;
        }
        return result;
    };
    

  • 0
    W

    Your code is great and easy understanding. I also try to use Javascript to code it. But I don't know why I fail in the test case. I test my code by using the test case which I failed, I passed and get the same result as estimated result. But when I submit, it still failed. Can you help me to solve the problem? I don;t use stack.

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

  • 0

    @Weidong_Diao Yeah I've tried your code, submission result for [1,2] is [1,1,2] but expected is [1,2], however if I input [1,2] for a test, the output and expected output are the same. So don't worry, may be a bug for Leetcode🙃


Log in to reply
 

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