Straightforward Python Solution


  • 0

    This solution serves to provide an easier way to solve this question than other solution that use confusing expression for the postion that should be filled out

    class Solution(object):
        def printTree(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[str]]
            """
            row = self.findMaxHeight(root)
            col = 2 ** row - 1
            self.tree = [["" for _ in range(col)] for _ in range(row)]
            self.fillTree(root, 0, 0, col)
            return self.tree
    
        def fillTree(self, root, row, left, right):
            if root == None:
                return
            else:
                mid = left + (right - left) / 2 
                self.tree[row][mid] = str(root.val)
                self.fillTree(root.left, row + 1, left, mid - 1)
                self.fillTree(root.right, row + 1, mid + 1, right)
                return
    
        def findMaxHeight(self, root):
            if root == None:
                return 0
            else:
                return 1 + max(self.findMaxHeight(root.left), self.findMaxHeight(root.right))
    

Log in to reply
 

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