102.|102. Binary Tree Level Order Traversal (Medium)

Description: 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],
102.|102. Binary Tree Level Order Traversal (Medium)
文章图片
【102.|102. Binary Tree Level Order Traversal (Medium)】return its level order traversal as:
102.|102. Binary Tree Level Order Traversal (Medium)
文章图片
Solution:

class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if root == None: return []node_ls = [root] value_ls = [] value_cache = [root.val]def helper(node_ls): cache = [] for node in node_ls: if node != None: cache.append(node.left) cache.append(node.right) return cachewhile value_cache: value_ls.append(value_cache) node_ls = helper(node_ls) value_cache = [n.val for n in node_ls if n != None]return value_ls

Runtime: 40 ms, faster than 82.05% of Python3 online submissions for Binary Tree Level Order Traversal.
Memory Usage: 13.5 MB, less than 39.42% of Python3 online submissions for Binary Tree Level Order Traversal.

    推荐阅读