102. Binary Tree Level Order Traversal

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]
]

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution(object):
    from collections import deque
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return []
        queue = deque()
        result = []
        temp = []
        queue.append(root)
        temp.append(root.val)
        result.append(temp)
        while queue:
            size = len(queue) # the size if the num of node in current level
            temp = []
            for i in range(size): 
                cur = queue.popleft()
                if cur.left:
                    queue.append(cur.left)
                    temp.append(cur.left.val)
                if cur.right:
                    queue.append(cur.right)
                    temp.append(cur.right.val)
            if temp == []:
                break
            result.append(temp)
        return result

请多多指教。

文章标题:102. Binary Tree Level Order Traversal

本文作者:顺强

发布时间:2020-04-13, 23:59:00

原始链接:http://shunqiang.ml/leetcode-102-binary-tree-level/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏