9 lines python code

  • 4
    class Solution(object):
        def levelOrder(self, root):
            if root is None: return []
            q = [[root]]
            for level in q:
                record = []
                for node in level:
                    if node.left: record.append(node.left)
                    if node.right: record.append(node.right)
                if record: q.append(record)
            return [[x.val for x in level] for level in q]

  • 0

    Are you a chinese?
    python code is much cleaner than other language.
    but i have a question about your answer:why it is ok if you change the "q" under the statment"for level in q" but your traversal of q is still make the right output?

  • 0

    It might be because Python is not thread safe, it allow developer to change the list. You can also do this in Java with for(int i = 0; i<q.size(); i++)

  • 0

    Thanks for your explanation.

Log in to reply

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