Accepted JavaScript solution


  • 0
    D
    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {number[]}
     */
    var preorderTraversal = function(root) {
        if(!root){
            return [];
        }
        
        let stack = [];
        let preArr = [];
        
        stack.push(root);
        
        while(stack.length > 0){
            let node = stack[stack.length-1];
            if(node){
    
                if(!node.isDone){
                    preArr.push(node.val);
                    node.isDone = true;
                }
    
                node = node.left;
                
                if(node && !node.isDone){
                    stack.push(node);
                    continue;
                }
            }
            
            node = stack[stack.length-1];
            if(node){
                node = node.right;
                
                if(node && !node.isDone){
                    stack.push(node);
                    continue;
                }
            }
            
            node = stack.pop();
        }
    
        
        return preArr;
        
    };
    
    

Log in to reply
 

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