【Leetcode】107—Binary Tree Level
2019-07-15 本文已影响0人
Gaoyt__
一、题目描述
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
二、代码实现
相关题目:102
# 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]]
"""
if root == None: return []
queue = [root]
res = []
while len(queue):
layer = []
for i in range(len(queue)):
cur = queue.pop(0)
layer.append(cur.val)
if cur.left: queue.append(cur.left)
if cur.right: queue.append(cur.right)
res.append(layer)
return res[::-1]