首页 > 代码库 > 【leetcode】Binary Tree Level Order Traversal

【leetcode】Binary Tree Level Order Traversal

class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        ret = []
        if not root:
            return ret
        max_dep = 0
        queue = []
        p = 0
        q = 1
        queue.append((root,1))
        while p < q:
            current_dep = queue[p][1]
            node = queue[p][0]
            if max_dep < current_dep:
                ret.append([])
                max_dep = current_dep
            ret[current_dep - 1].append(node.val)
            for node in (node.left,node.right):
                if node:
                    queue.append((node,current_dep + 1))
                    q += 1
            p += 1
        return ret
class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        ret = []
        if not root:
            return ret
        level = [root]
        while level:
            ret.append([node.val for node in level])
            level = [leaf for node in level for leaf in (node.left,node.right) if leaf]
        return ret
class Solution(object):
    def do(self, p, level):
        if (not p):
            return
        if level >= len(self.list):
            self.list.append([p.val])
        else:
            self.list[level].append(p.val)
        self.do(p.left,  level + 1)
        self.do(p.right, level + 1)
    
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        self.list = []
        self.do(root,0)
        return self.list

用三种方法写了一下,第二种有点意思,玩玩python了

【leetcode】Binary Tree Level Order Traversal