将有序数组转换为二叉搜索树
最后更新于:2022-04-02 04:22:40
[TOC]
## 将有序数组转换为二叉搜索树
给你一个整数数组`nums`,其中元素已经按**升序**排列,请你将其转换为一棵**高度平衡**二叉搜索树。
![](https://assets.leetcode.com/uploads/2021/02/18/btree1.jpg)
解答
```
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func sortedArrayToBST(nums []int) *TreeNode {
return helper(nums,0,len(nums)-1)
}
func helper(nums []int,left,right int)*TreeNode {
if left>right {
return nil
}
mid:=(left+right)/2
root:=&TreeNode{Val:nums[mid]}
root.Left=helper(nums,left,mid-1)
root.Right=helper(nums,mid+1,right)
return root
}
```
';