Simple Python Solution


  • 3
    J
    def isValidSerialization(self, preorder):
        preorder = preorder.split(',')
        balance = 1
        for item in preorder:
            balance -= 1
            if balance < 0:
                return False
            if item != '#':
                balance += 2
        return balance == 0
    

    ##Every parent node will introduce 2 children. One child must have a parent. So if a node has 2 children, it should add 2, otherwise do not add. For every node introduced, it should -1 to balance parent number. Initial balance is 1 because root is special case.


  • 0
    A

    Nice and simple!


Log in to reply
 

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