Why case [3,2,2] is expected to be 1? (close and with my solution)


  • 0
    A

    [3,2,2] should be 2, right?

    3->2 which is length 2


  • 0
    A

    Oh... it is longest consecutive sequence so only for the increasing number.
    so 3->2 isn't count as consecutive sequence.
    Here's my Python solution.

    def longestConsecutive(self, root):
        if not root:
            return 0
            
        def trace(root, now_len, preval, sign):
            if now_len == 1:
                if preval-root.val == -1:
                    now_len += 1
                    sign = '+'
                else:
                    sign = '*'
                       
            else: # more than length 1
                if preval-root.val == -1 and sign == '+':
                    now_len += 1
                else:
                    now_len = 1
                    sign = '*'
            
            if now_len > self.ans:
                self.ans = now_len
            
            if root.left:
                trace(root.left, now_len, root.val, sign)
            if root.right:
                trace(root.right, now_len, root.val, sign)
                
        self.ans = 1
        if root.left:
            trace(root.left, 1, root.val, '*')
        if root.right:
            trace(root.right, 1, root.val, '*')
        return self.ans

  • 0
    S

    [3,2,2] means the tree is like
    3
    2 2
    and the question is asking a ascending order which means parents value must be less than children value.


Log in to reply
 

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