Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 2cfe0bd

Browse files
aQuaaQua
aQua
authored and
aQua
committed
107 accepted. 6ms.
1 parent dd684db commit 2cfe0bd

File tree

3 files changed

+103
-0
lines changed

3 files changed

+103
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# [107. Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii/)
2+
3+
## 题目
4+
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).
5+
6+
7+
For example:
8+
Given binary tree [3,9,20,null,null,15,7],
9+
```
10+
3
11+
/ \
12+
9 20
13+
/ \
14+
15 7
15+
```
16+
17+
return its bottom-up level order traversal as:
18+
```
19+
[
20+
[15,7],
21+
[9,20],
22+
[3]
23+
]
24+
```
25+
26+
## 解题思路
27+
28+
见程序注释
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package Problem0107
2+
3+
import (
4+
"github.com/aQuaYi/LeetCode-in-Golang/kit"
5+
)
6+
7+
type TreeNode = kit.TreeNode
8+
9+
func levelOrderBottom(root *TreeNode) [][]int {
10+
temp := [][]int{}
11+
12+
var dfs func(*TreeNode, int)
13+
dfs = func(root *TreeNode, level int) {
14+
if root == nil {
15+
return
16+
}
17+
18+
// 出现了新的 level
19+
if level >= len(temp) {
20+
temp = append(temp, []int{})
21+
}
22+
temp[level] = append(temp[level], root.Val)
23+
24+
dfs(root.Left, level+1)
25+
dfs(root.Right, level+1)
26+
}
27+
28+
dfs(root, 0)
29+
30+
n := len(temp )
31+
res := make([][]int , n )
32+
for i:=0; i<n ; i++{
33+
res[i] = temp[n-i-1]
34+
}
35+
36+
return res
37+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package Problem0107
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/aQuaYi/LeetCode-in-Golang/kit"
8+
"github.com/stretchr/testify/assert"
9+
)
10+
11+
func Test_Problem0107(t *testing.T) {
12+
ast := assert.New(t)
13+
14+
// tcs is testcase slice
15+
tcs := []struct {
16+
pre, in []int
17+
ans [][]int
18+
}{
19+
20+
{
21+
[]int{3, 9, 20, 15, 7},
22+
[]int{9, 3, 15, 20, 7},
23+
[][]int{
24+
[]int{15, 7},
25+
[]int{9, 20},
26+
[]int{3},
27+
},
28+
},
29+
30+
// 可以多个 testcase
31+
}
32+
33+
for _, tc := range tcs {
34+
fmt.Printf("~~%v~~\n", tc)
35+
36+
ast.Equal(tc.ans, levelOrderBottom(kit.PreIn2Tree(tc.pre, tc.in)), "输入:%v", tc)
37+
}
38+
}

0 commit comments

Comments
 (0)