leetcode107.Binary Tree Level Or

2020-07-02  本文已影响0人  就是果味熊

原题链接https://leetcode.com/problems/binary-tree-level-order-traversal-ii/

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]

基本与该题解题方法一样,都是层序遍历,只是本题从底层开始输出,本来准备从顶层输出到栈,然后出栈到list,所以用res_stack命名了。后来直接用list[::-1]求解了,也可以双端队列从左边加入队列。

from collections import deque
class Solution:
    def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return []
        
        deques = deque()
        res_stack = []
        # res_stack = deque()
        deques.append(root)
        count = 1
        while deques:
            res = []
            n = count
            count = 0
            i = 0
            while i < n:
                item = deques.popleft()
                res.append(item.val)
                i += 1
                if item.left:
                    count += 1
                    deques.append(item.left)
                if item.right:
                    count += 1
                    deques.append(item.right)
            res_stack.append(res)
            # res_stack.appendleft(res)
        return res_stack[::-1]
        # return res_stack

上一篇下一篇

猜你喜欢

热点阅读