leetcode--二叉树的层次遍历
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [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 = Noneclass 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% 的用户
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。