107. 二叉树的层序遍历 II

107. 二叉树的层序遍历 II
思路:
中序遍历+同一深度节点放在一个数组中+翻转

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
        '''
        思路:
            中序遍历后将结果翻转
        '''
        res = []
        if not root:
            return res
        
        q = [root]
        while q:
            temp = []
            length = len(q)
            for _ in range(length):
                node = q.pop(0)
                temp.append(node.val)
                
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            res.append(temp)
        return res[::-1]
上一篇:最长的美好子字符串


下一篇:动态规划学习记录-5 打家劫舍