JavaScript pre-order simple 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 longestConsecutive = function(root) {
        
        if(!root){
            return 0;
        }
        
        let max = -1;
        
        preorder(root, null, null);
        
        return max;
        
        function preorder(root, prev, seq){
            
            if(root){
                
                let currSeq = 1;
                if(Number.isInteger(prev) && root.val == prev + 1){
                    currSeq = seq;
                }
                
                max = Math.max(max, currSeq);
                prev = root.val;
                
                preorder(root.left, prev, currSeq + 1);
                preorder(root.right, prev, currSeq + 1);
                
            }
            
        }
        
    };
    
    
    

Log in to reply
 

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