preorderTraversal with Stack in JavaScript


  • 0
    N
    const Stack = function() {
        this._storage = {};
        this._startIndex = 0;
    };
    
    Stack.prototype.push = function(val) {
        this._storage[++this._startIndex] = val;
    };
    
    Stack.prototype.pop = function() {
        if(this.size()) {
            let remove = this._storage[this._startIndex];
            delete this._storage[this._startIndex--];
            return remove;
        }
    };
    
    Stack.prototype.size = function() {
        return this._startIndex;
    };
    
    
    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {number[]}
     */
    const preorderTraversal = function(root) {
        let response = [];
        
        if(!root) {
            return response;
        }
        
        let s = new Stack();
        s.push(root);
        
        while(s.size()) {
            let d = s.pop();
            
            response.push(d.val);
            
            if(d.right) {
                s.push(d.right);
            }
            
            if (d.left) {
                s.push(d.left);
            }
        }
        
        return response;
    };
    

Log in to reply
 

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