JavaScript solution using stack with explanation, Beats 95%


  • 0
    X
    // push nodes of a level to a stack
    // then keep getting next level's while popping current one's value to result
    // break loop when the new stack is empty
    
    var preorderTraversal =  function(root) {
    
    if (root == null){
        return [];
    }
    if (root.left == null && root.right == null){
        return [root.val];
    }
    var result = [];
    
    var nodes = [root];
    var tempNodes = [];
    while (nodes.length > 0){
        while (nodes.length > 0){
            var node = nodes.pop();
            result.push(node.val);
            if (node.right){
                tempNodes.push(node.right);
            }
            if (node.left){
                nodes.push(node.left);
            }
        }
        
        nodes = tempNodes;
        
     }
    return result;
    };

Log in to reply
 

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