简繁EN

LeetCodeNo. 088

[LeetCode with Python] 107. Binary Tree Level Order Traversal II

Contents

Problem

Problem page: https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
Topics: Tree, Breadth-first Search
Difficulty: Easy
Similar problems: (E) Binary Tree Level Order Traversal

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,#,#,15,7},

1
2
3
4
5
  3
/ \
9 20
/ \
15 7

return its bottom-up level order traversal as:

1
2
3
4
5
[
[15,7],
[9,20],
[3]
]

confused what "{1,#,2,3}" means?

OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

1
2
3
4
5
6
7
  1
/ \
2 3
/
4
\
5

The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".


Analysis

I wonder if the idea was to use recursion to work up from the leaf nodes to the root node, adding each node to the corresponding level in the two-dimensional result array?
I just wanted to keep it simple, so I reverse the result array from Binary Tree Level Order Traversal...


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution:

# @param root, a tree node
# @return a list of lists of integers
def levelOrder(self, root):
if None == root:
return [ ]
results = [ [root.val] ]
reflist1 = [root]
while True:
reflist2 = [ ]
result = [ ]
for i in range(0, len(reflist1)):
cur = reflist1[i]
if None != cur.left:
reflist2.append(cur.left)
result.append(cur.left.val)
if None != cur.right:
reflist2.append(cur.right)
result.append(cur.right.val)
if 0 == len(reflist2):
break
results.append(result)
reflist1 = reflist2
return results

def levelOrderBottom(self, root):
results = self.levelOrder(root)
results.reverse()
return results

Article link: https://xnerv.wang/en/leetcode-binary-tree-level-order-traversal-ii/