剑指 Offer 32 - II. 从上到下打印二叉树 II
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
提示:
节点总数 <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof
# 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 [] queue,res=[root],[] while queue: n=len(queue) res.append([]) for i in range(n): node=queue[i] res[-1].append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) queue=queue[n:] return res
# 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=[] def add_to_res(level,node): if level>len(res)-1: res.append([]) res[level].append(node.val) if node.left: add_to_res(level+1,node.left) if node.right: add_to_res(level+1,node.right) add_to_res(0,root) return res