您的位置:首页 > 编程语言 > Python开发

Leetcode107. 二叉树的层次遍历 II(python3)

2019-03-01 10:44 344 查看

Leetcode107. 二叉树的层次遍历 II
题目描述:
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

解法1:

# 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):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root == None:
return []
q=[root]
res=[]
while q:
tem=[]
q2=[]
for item in q:
tem.append(item.val)
if item.left:
q2.append(item.left)
if item.right:
q2.append(item.right)
res.append(tem)
q=q2
return res[::-1]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: