给定一个二叉树,返回其按层次遍历的节点值,即逐层从左到右访问所有节点
在子函数中传入层数,子树层数+1即可
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.res = []
def levelOrder(self, root: TreeNode) -> List[List[int]]:
def addLevel(tree: TreeNode, level: int):
if tree is None:
return
if len(self.res) < level:
self.res.append([tree.val])
else:
self.res[level - 1].append(tree.val)
addLevel(tree.left, level + 1)
addLevel(tree.right, level + 1)
addLevel(root, 1)
return self.res