Leetcode刷题记录——剑指 Offer 32 - II. 从上到下打印二叉树 II

Leetcode刷题记录——剑指 Offer 32 - II. 从上到下打印二叉树 II_第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]]:
        if root == None:
            return self.res
        self.func(root,0)
        return self.res


    def func(self,root,depth):
        if root == None:
            return 0
        else:
            if depth >= len(self.res):
                self.res.append([root.val])
            else:
                self.res[depth].append(root.val)
            self.func(root.left,depth + 1)
            self.func(root.right,depth + 1)

你可能感兴趣的:(python编程技巧,leetcode)