乐趣区

关于golang:Leetcode专题数组108将有序数组转换为二叉搜索树

力扣链接:https://leetcode-cn.com/probl…
解题思路:
这道题自身比较简单,是一个简略递归就能够解决的,首先找到有序队列的中位数,作为二叉树的根节点,而后右边数组为左子树的节点,左边数组为左子树的节点,顺次递归即可

/**
 * 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, low, high int) *TreeNode {
    if low > high {return nil}
    mid := (high - low) >> 1 + low
    root := &TreeNode{Val:nums[mid]}
    root.Left = helper(nums, low, mid - 1)
    root.Right = helper(nums, mid + 1, high)
    return root
}
退出移动版