Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit afc46ee

Browse files
author
Shuo
authored
Merge pull request #419 from openset/develop
Add: Convert Sorted Array to Binary Search Tree
2 parents 264e8ad + f5893ea commit afc46ee

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,21 @@
11
package convert_sorted_array_to_binary_search_tree
2+
3+
import . "github.com/openset/leetcode/internal/kit"
4+
5+
/**
6+
* Definition for a binary tree node.
7+
* type TreeNode struct {
8+
* Val int
9+
* Left *TreeNode
10+
* Right *TreeNode
11+
* }
12+
*/
13+
func sortedArrayToBST(nums []int) *TreeNode {
14+
var node *TreeNode
15+
if l := len(nums); l > 0 {
16+
node = &TreeNode{Val: nums[l/2]}
17+
node.Left = sortedArrayToBST(nums[0 : l/2])
18+
node.Right = sortedArrayToBST(nums[l/2+1:])
19+
}
20+
return node
21+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,28 @@
11
package convert_sorted_array_to_binary_search_tree
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
7+
. "github.com/openset/leetcode/internal/kit"
8+
)
9+
10+
type caseType struct {
11+
input []int
12+
expected []int
13+
}
14+
15+
func TestSortedArrayToBST(t *testing.T) {
16+
tests := [...]caseType{
17+
{
18+
input: []int{-10, -3, 0, 5, 9},
19+
expected: []int{0, -3, 9, -10, 5},
20+
},
21+
}
22+
for _, tc := range tests {
23+
output := TreeNode2SliceInt(sortedArrayToBST(tc.input))
24+
if !reflect.DeepEqual(output, tc.expected) {
25+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
26+
}
27+
}
28+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /