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],

return its bottom-up level order traversal as:

Solution in python:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
        if root == None:
            return []
        result = []
        level = []
        queue = [root]
        size = 1
        num = 0
        while size > 0:
            temp = queue.pop(0)
            level.append(temp.val)
            size -= 1
            if temp.left:
                queue.append(temp.left)
                num += 1
            if temp.right:
                queue.append(temp.right)
                num += 1
            if size == 0:
                result.insert(0, level)
                size = num
                num  = 0
                level = []
        return result
最后修改日期: 2021年1月6日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。