Skip to content

Commit 64ebccd

Browse files
committed
convert_sorted_array_to_binary_search_tree
1 parent 9bdc0c0 commit 64ebccd

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
9494
#### [105. construct binary tree from preorder and inorder traversal](https://github.com/hitzzc/go-leetcode/tree/master/construct_binary_tree_from_preorder_and_inorder_traversal)
9595
#### [106. construct binary tree from inorder and postorder traversal](https://github.com/hitzzc/go-leetcode/tree/master/construct_binary_tree_from_inorder_and_postorder_traversal)
9696
#### [107. Binary Tree Level Order Traversal II](https://github.com/hitzzc/go-leetcode/tree/master/binary_tree_level_order_traversal_II)
97+
#### [108. Convert Sorted Array to Binary Search Tree](https://github.com/hitzzc/go-leetcode/tree/master/convert_sorted_array_to_binary_search_tree)
9798

9899

99100

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package convert_sorted_array_to_binary_search_tree
2+
3+
type TreeNode struct {
4+
Val int
5+
Left *TreeNode
6+
Right *TreeNode
7+
}
8+
9+
func sortedArrayToBST(nums []int) *TreeNode {
10+
return helper(nums, 0, len(nums)-1)
11+
}
12+
13+
func helper(nums []int, i, j int) *TreeNode {
14+
if len(nums) == 0 || i > j || i < 0 || j >= len(nums) {
15+
return nil
16+
}
17+
if i == j {
18+
return &TreeNode{Val: nums[i]}
19+
}
20+
mid := i + (j-i)/2
21+
root := &TreeNode{Val: nums[mid]}
22+
root.Left = helper(nums, i, mid-1)
23+
root.Right = helper(nums, mid+1, j)
24+
return root
25+
}

0 commit comments

Comments
 (0)