给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回其层次遍历结果:
[ [3], [9,20], [15,7] ]
# 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]]:
if not root:
return []
res = []
cur_node = [root]
next_node = []
res.append([i.val for i in cur_node])
while cur_node or next_node:
for node in cur_node:
if node.left:
next_node.append(node.left)
if node.right:
next_node.append(node.right)
if next_node:
res.append([
i.val for i in next_node
])
cur_node = next_node
next_node = []
return res
执行用时 : 80 ms, 在Binary Tree Level Order Traversal的Python3提交中击败了26.32% 的用户
内存消耗 : 13.2 MB, 在Binary Tree Level Order Traversal的Python3提交中击败了98.08% 的用户
转载于:https://blog.51cto.com/12080420/2389326