04_二叉树的层次遍历

2019-11-12  本文已影响0人  butters001
# 这道题在 初级算法 中出现过 那次用的是迭代

# 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]]
        """
        if not root:
            return []

        res = []

        def helper(node, level):
            if len(res) == level:
                res.append([])
            res[level].append(node.val)
            if node.left:
                helper(node.left, level + 1)
            if node.right:
                helper(node.right, level + 1)

        helper(root, 0)
        return res

上一篇下一篇

猜你喜欢

热点阅读