题目大意

层序输出二叉树,这次是从最下层输出到根节点

解题思路

只要在Binary Tree Level Order Traversal的基础上加一行反转

代码

DFS代码请看上面一题,都只要加一行。

BFS

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

class Solution(object):
    def levelOrderBottom(self, root):
        """ :type root: TreeNode :rtype: List[List[int]] """
        tree = []
        if not root:
            return tree
        curr_level = [root]
        # print(type(root), type(curr_level)) # (<class 'precompiled.treenode.TreeNode'>, <type 'list'>)
        # print(curr_level) # 作为list,却并不能遍历整个树
        while curr_level:
            level_list = []
            next_level = []
            for temp in curr_level:
                level_list.append(temp.val)
                if temp.left:
                    next_level.append(temp.left)
                if temp.right:
                    next_level.append(temp.right)
            tree.append(level_list)
            curr_level = next_level
        tree.reverse()
        return tree

总结

  1. tree.reverse()反转