给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [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% 的用户
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。