题目链接:
https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof/
题意:
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
题解:
与 I 类似的层次遍历,不过要注意遍历的时候顺便记录层数。
代码:
# 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 root == None:
return []
q,ret,tmp= [],[],[]
q.append([root,1])
depth = 1
while len(q)>0 :
top = q[0]
q.pop(0)
if top[1]>depth:
ret.append(tmp)
depth +=1
tmp =[]
tmp.append(top[0].val)
if top[0].left !=None :q.append([top[0].left,top[1]+1])
if top[0].right != None :q.append([top[0].right,top[1]+1])
ret.append(tmp)
return ret