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

Leetcode刷题记录——剑指 Offer 32 - III. 从上到下打印二叉树 III_第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 = []
        self.d = True
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if root == None:
            return self.res
        self.func(root,0)
        for i,each in enumerate(self.res):
            if i % 2 != 0:
                self.res[i] = self.res[i][::-1]
        return self.res
    def func(self,root,depth):
        if root == None:
            return 0
        elif depth >= len(self.res):# and depth % 2 == 0:
            self.res.append([root.val])
        elif depth <len(self.res):

            self.res[depth].append(root.val)
        self.func(root.left,depth + 1)
        self.func(root.right,depth + 1)

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