Accepted JS iterative anwer


  • 1
    J
    var preorderTraversal = function(root) {
        var nodes = [];
        if (root !== null && typeof root.val !== "undefined") {
            var stack = [root];
            while (stack.length) {
                var node = stack.pop();
                if (node.val !== null) {
                    nodes.push(node.val);
                }
                if (node.right !== null) {
                    stack.push(node.right);
                }
                if (node.left !== null) {
                    stack.push(node.left);
                }
            }
        }
        return nodes;
    };
    

    this was my recursive one ftr:

    var preorderTraversal = function(root) {
        var nodes = [];
        
        var visit = function(node) {
            if (node === null || typeof node === "undefined") {
                return;
            }
            nodes.push(node.val);
            visit(node.left);
            visit(node.right);
        }
        visit(root);
        return nodes;
    };

Log in to reply
 

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