题解 | #将升序数组转化为平衡二叉搜索树# |Golang
将升序数组转化为平衡二叉搜索树
https://www.nowcoder.com/practice/7e5b00f94b254da599a9472fe5ab283d
package main import . "nc_tools" /* * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @return TreeNode类 */ func sortedArrayToBST( nums []int ) *TreeNode { return dfs(nums, 0, len(nums)-1) } func dfs(nums []int, b int, e int) *TreeNode { if b > e { return nil } mid := b + (e - b)/2 + (e - b)%2 node := TreeNode{nums[mid],nil,nil} node.Left = dfs(nums, b, mid-1) node.Right = dfs(nums, mid+1, e) return &node }