Clean Python Solution


  • 0

    Use index to record each level.

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def widthOfBinaryTree(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            self.res = 1
            self.go([root],[0])
            return self.res
            
        def go(self, level, coor):
            
            # get length of current level and go to next level
            # print level
            # print coor
            
            if not level:
                return 0
            
            length = max(coor)-min(coor)+1
            self.res = max(self.res, length)
            
            new_level = []
            new_coor = []
            for i, element in enumerate(level):
                if element.left:
                    new_level.append(element.left)
                    new_coor.append(coor[i]*2+0)
                if element.right:
                    new_level.append(element.right)
                    new_coor.append(coor[i]*2+1)
            self.go(new_level, new_coor)
    

Log in to reply
 

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