Skip to content
This repository was archived by the owner on Apr 27, 2025. It is now read-only.

Commit 4d9f6ad

Browse files
committed
107. Binary Tree Level Order Traversal II
1 parent d82259b commit 4d9f6ad

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# 107. Binary Tree Level Order Traversal II
2+
3+
### 2017-03-22
4+
5+
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).
6+
7+
For example:
8+
Given binary tree `[3,9,20,null,null,15,7]`,
9+
10+
```
11+
3
12+
/ \
13+
9 20
14+
/ \
15+
15 7
16+
17+
```
18+
19+
return its bottom-up level order traversal as:
20+
21+
```
22+
[
23+
[15,7],
24+
[9,20],
25+
[3]
26+
]
27+
```
28+
29+
30+
31+
# Solution
32+
33+
```swift
34+
/**
35+
* Definition for a binary tree node.
36+
* public class TreeNode {
37+
* public var val: Int
38+
* public var left: TreeNode?
39+
* public var right: TreeNode?
40+
* public init(_ val: Int) {
41+
* self.val = val
42+
* self.left = nil
43+
* self.right = nil
44+
* }
45+
* }
46+
*/
47+
class Solution {
48+
func levelOrderBottom(_ root: TreeNode?) -> [[Int]] {
49+
var res = [[Int]]()
50+
guard let n = root else { return res }
51+
var layer = [n]
52+
while layer.count > 0 {
53+
var temp = [Int]()
54+
for i in 0..<layer.count {
55+
let n = layer.removeFirst()
56+
temp.append(n.val)
57+
if let l = n.left { layer.append(l) }
58+
if let r = n.right { layer.append(r) }
59+
}
60+
res.insert(temp, at: 0)
61+
}
62+
return res
63+
}
64+
}
65+
```
66+

0 commit comments

Comments
 (0)