Skip to content

Commit 412107c

Browse files
aQuaaQua
aQua
authored and
aQua
committed
108 accepted. 259ms > 248ms.
1 parent 31af2b4 commit 412107c

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# [108. Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/)
2+
3+
## 题目
4+
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
5+
6+
## 解题思路
7+
> 高度平衡二叉树是每一个节点的两个子树的深度差不能超过1。
8+
见程序注释
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package Problem0108
2+
3+
import (
4+
"github.com/aQuaYi/LeetCode-in-Golang/kit"
5+
)
6+
7+
type TreeNode = kit.TreeNode
8+
9+
func sortedArrayToBST(nums []int) *TreeNode {
10+
n := len(nums)
11+
if n == 0 {
12+
return nil
13+
}
14+
15+
if n == 1 {
16+
return &TreeNode{
17+
Val: nums[0],
18+
}
19+
}
20+
21+
return &TreeNode{
22+
Val: nums[n/2],
23+
Left: sortedArrayToBST(nums[:n/2]),
24+
Right: sortedArrayToBST(nums[n/2+1:]),
25+
}
26+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package Problem0108
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/aQuaYi/LeetCode-in-Golang/kit"
8+
9+
"github.com/stretchr/testify/assert"
10+
)
11+
12+
func Test_Problem0108(t *testing.T) {
13+
ast := assert.New(t)
14+
15+
// tcs is testcase slice
16+
tcs := []struct {
17+
nums []int
18+
pre []int
19+
}{
20+
21+
{
22+
[]int{},
23+
nil,
24+
},
25+
26+
{
27+
[]int{1, 2, 3, 4, 5, 6, 7},
28+
[]int{4, 2, 1, 3, 6, 5, 7},
29+
},
30+
31+
// 可以多个 testcase
32+
}
33+
34+
for _, tc := range tcs {
35+
fmt.Printf("~~%v~~\n", tc)
36+
37+
ast.Equal(tc.pre, kit.Tree2Preorder(sortedArrayToBST(tc.nums)), "输入:%v", tc)
38+
}
39+
}

0 commit comments

Comments
 (0)