simple early return, using modular division


  • 0

    The rationale:

    • Total number of nodes should be an odd number. More specifically, the number of '#' (empty nodes) should be 1 more than the number of real nodes, which is why 'cnt' is initialized to 1. Thus, when while loop breaks, we just check if we have reached the end of array and cnt is not 0.
    def isValidSerialization(self, preorder):
        arr = preorder.split(',')
        if len(arr)==1: return arr[0]=='#'
        if len(arr)%2==0: return False
    
        cnt, i = 1, 0 
        while i < len(arr) and cnt > 0:
          if arr[i] != '#':
              cnt += 1
          else:
              cnt -= 1
          i+=1
        return not(cnt==0 and i < len(arr))
    

Log in to reply
 

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