leetcodeBinary Tree Level Order Traversal

Posted syb3181

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcodeBinary 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了

以上是关于leetcodeBinary Tree Level Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章

leetcodeBinary Tree Level Order Traversal

LeetcodeBinary Tree Maximum Path Sum

leetcodebinary-tree-maximum-path-sum

[Leetcode] Binary Tree Level Order Traversal

[leetcode tree]103. Binary Tree Zigzag Level Order Traversal

102. Binary Tree Level Order Traversal