102 Binary Tree Level Order Traversal

102 Binary Tree Level Order Traversal 

class Solution:
    # @param {TreeNode} root
    # @return {integer[][]}
    def levelOrder(self, root):
        if root == None:
            return []
        ans, q, level = [], [root, None], []
        while True:
            node = q.pop(0)
            if node != None:
                level.append(node.val)
                if node.left != None:
                    q.append(node.left)
                if node.right != None:
                    q.append(node.right)
            else:
                ans.append(level)
                level = []
                if q == []:
                    break
                else:
                    q.append(None)
        return ans

 

posted @ 2015-07-23 01:26  dapanshe  阅读(115)  评论(0编辑  收藏  举报