Easy Python code, using (node, height) tuple for outputing array


  • 0
    W
    class Solution(object):
        def levelOrder(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            if root==None:
                return []
            q,re,re_line=[],[],[]
            height,keep_height=1,1
            q.append((root,1))
            while q:
                node,height=q.pop(0)
                print node.val,height, keep_height
                if height==keep_height+1:
                    re.append(re_line)
                    re_line=[]
                    re_line.append(node.val)
                elif height==keep_height:
                    re_line.append(node.val)
                keep_height=height
                if node.left:
                    q.append((node.left,height+1))
                if node.right:
                    q.append((node.right,height+1))
            re.append(re_line)
            return re
    

    Introducing height, height of child node =height of parent node+1; so the different level is known.


Log in to reply
 

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