[leetcode-python3] 102. Binary Tree Level Order Traversal

1122 ワード

102. Binary Tree Level Order Traversal - python3
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
My Answer 1: Accepted (Runtime: 32 ms - 80.94%/Memory Usage: 14.7 MB - 35.94%)
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if root is None:
            return
        queue = [root]
        result = []
        while queue:
            length = len(queue)
            temp = []
            for i in range(0, length):
                root = queue.pop(0)
                temp.append(root.val)
                if root.left:
                    queue.append(root.left)
                if root.right:
                    queue.append(root.right)
            result.append(temp)
        
        return result
BFSでのlevel orderループの使用
レベルを表す「queue長」を繰り返し、リストに値を囲みresultを入れます.