Share my simple 13-line Java Solution


  • 0
        int max = 0;
        public int longestConsecutive(TreeNode root) {
            helper(root, 0, 0);
            return max;
        }
        public void helper(TreeNode root, int prevVal, int prevLen){
            max = Math.max(max, prevLen);
            if(root==null) return;
            if(root.val==prevVal+1) prevLen = prevLen+1;
            else prevLen = 1;
            helper(root.left, root.val, prevLen);
            helper(root.right, root.val, prevLen);
        }
    

Log in to reply
 

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