Iterative Javascript DFS


  • 0
    R
    var longestConsecutive = function(root) {
        if(!root) return 0;
        var ans = 0, stack = [[root, 1]];
        while(stack.length > 0) {
            var node, length, a;
            a = stack.pop();        
            node = a[0], length = a[1];
            ans = Math.max(ans, length);
            if(node.right) {
                var l = node.right.val -1 == node.val ? 1 + length : 1;
                stack.push([node.right, l]);
            } 
            if (node.left) {
                var l = node.left.val -1 == node.val ? 1 + length : 1;
                stack.push([node.left, l]);
            }
        }
        return ans;
    };
    

Log in to reply
 

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