美文网首页leetcode刷题总结 python版
leetcode 102. Binary Tree Level

leetcode 102. Binary Tree Level

作者: PJCK | 来源:发表于2019-06-23 08:43 被阅读0次

    Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
    For example:
    Given binary tree [3,9,20,null,null,15,7],

      3
       / \
      9  20
        /  \
       15   7
    

    return its level order traversal as:

    [
      [3],
      [9,20],
      [15,7]
    ]
    

    这是一个层次遍历,可以用list模拟队列,不能用queue库,因为queue库似乎没有pop,而list有pop。
    python代码:

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    class Solution:
        def levelOrder(self, root: TreeNode) -> List[List[int]]:
            q = []
            q.append(root)
            nums = []
            if not root:
                return []
            while len(q):
                length = len(q)
                num = []
                for i in range(length):
                    T = q[0]
                    q.pop(0)
                    num.append(T.val)
                    if T.left:
                        q.append(T.left)
                    if T.right:
                        q.append(T.right)
                nums.append(num)
            return nums
    

    相关文章

      网友评论

        本文标题:leetcode 102. Binary Tree Level

        本文链接:https://www.haomeiwen.com/subject/qyxiqctx.html