給定乙個二叉樹,返回其節點值自底向上的層次遍歷。 (即按從葉子節點所在層到根節點所在的層,逐層從左向右遍歷)
例如:
給定二叉樹 [3,9,20,null,null,15,7],
3 / \
9 20
/ \
15 7
返回其自底向上的層次遍歷為:
[ [15,7],
[9,20],
[3]
]1
2# definition for a binary tree node.
# class treenode:
# def __init__(self, x):
# self.val = x
# self.left = none
# self.right = none
class
solution:
deflevelorderbottom
(self, root):
""" :type root: treenode
:rtype: list[list[int]]
"""if root == none:
return
q,result = [root],
while q != :
temp =
for _ in range(len(q)):
node = q.pop(0)
if node.left:
if node.right:
result.insert(0,temp)
return result
# definition for a binary tree node.
# class treenode:
# def __init__(self, x):
# self.val = x
# self.left = none
# self.right = none
class
solution:
deflevelorderbottom
(self, root):
""" :type root: treenode
:rtype: list[list[int]]
"""if root == none:
return
parentsize = 1
childsize = 0
q = [root]
result =
while q != :
temp =
while parentsize>0:
node = q.pop(0)
parentsize -= 1
if node.left:
childsize += 1
if node.right:
childsize += 1
parentsize = childsize
childsize = 0
result.insert(0,temp)
return result
LeetCode 107 二叉樹的層次遍歷
題目描述 給定乙個二叉樹,返回其節點值自底向上的層次遍歷。即按從葉子節點所在層到根節點所在的層,逐層從左向右遍歷 例如 給定二叉樹 3,9,20,null,null,15,7 3 9 20 15 7返回其自底向上的層次遍歷為 15,7 9,20 3 解題思路 此題跟102基本一樣,就是在輸出時是自底...
leetCode 107 二叉樹層次遍歷II
按層次從頂至下遍歷,將每層結點加在佇列尾部,每次從頭部取出一層結點。使用棧將結果反轉。definition for a binary tree node.public class treenode class solution if root.right null stack.push temp 棧...
leetcode 107 二叉樹的層次遍歷 II
前言 python刷leetcode題解答目錄索引 正文 給定乙個二叉樹,返回其節點值自底向上的層次遍歷。即按從葉子節點所在層到根節點所在的層,逐層從左向右遍歷 例如 給定二叉樹 3,9,20,null,null,15,7 3 9 20 15 7返回其自底向上的層次遍歷為 15,7 9,20 3 d...