-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path108.go
More file actions
40 lines (36 loc) · 689 Bytes
/
Copy path108.go
File metadata and controls
40 lines (36 loc) · 689 Bytes
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
31
32
33
34
35
36
37
38
39
40
package main
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func sortedArrayToBST(nums []int) *TreeNode {
if len(nums) == 0 {
return nil
}
var buildTree func(int, int) *TreeNode
buildTree = func(left int, right int) *TreeNode {
if left > right {
return nil
}
node := &TreeNode{
Val: 0,
Left: nil,
Right: nil,
}
mid := (left + right) / 2
node.Val = nums[mid]
node.Left = buildTree(left, mid - 1)
node.Right = buildTree(mid + 1, right)
return node
}
return buildTree(0, len(nums) - 1)
}