问题链接
https://leetcode.com/explore/interview/card/top-interview-questions-easy/94/trees/628/
解题思路
1、先序遍历
2、每次记录层次,作为子数组的index
3、将每次的root节点append到指定层次的子数组中
具体代码
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res = []
self.preorder(res, 0, root)
return res
def preorder(self, res, level, root):
if root:
if len(res) < level + 1:
res.append([])
res[level].append(root.val)
self.preorder(res, level + 1, root.left)
self.preorder(res, level + 1, root.right)