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
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论