Golang | Leetcode Golang题解之第109题有序链表转换二叉搜索树

题目:

题解:

Go 复制代码
var globalHead *ListNode

func sortedListToBST(head *ListNode) *TreeNode {
    globalHead = head
    length := getLength(head)
    return buildTree(0, length - 1)
}

func getLength(head *ListNode) int {
    ret := 0
    for ; head != nil; head = head.Next {
        ret++
    }
    return ret
}

func buildTree(left, right int) *TreeNode {
    if left > right {
        return nil
    }
    mid := (left + right + 1) / 2
    root := &TreeNode{}
    root.Left = buildTree(left, mid - 1)
    root.Val = globalHead.Val
    globalHead = globalHead.Next
    root.Right = buildTree(mid + 1, right)
    return root
}
相关推荐
Navigator_Z5 小时前
LeetCode //C - 1033. Moving Stones Until Consecutive
c语言·算法·leetcode
We་ct11 小时前
LeetCode 72. 编辑距离:动态规划经典题解
前端·算法·leetcode·typescript·动态规划
m0_6294947312 小时前
LeetCode 热题 100-----17.缺失的第一个正数
数据结构·算法·leetcode
Tisfy12 小时前
LeetCode 0796.旋转字符串:暴力模拟
算法·leetcode·题解·模拟·字符串匹配
小雅痞14 小时前
[Java][Leetcode middle] 209. 长度最小的子数组
java·算法·leetcode
浅念-17 小时前
吃透栈:LeetCode 栈算法题全解析
数据结构·c++·算法·leetcode·职场和发展·
阿Y加油吧17 小时前
二刷 LeetCode:62. 不同路径 & 64. 最小路径和 复盘笔记
笔记·算法·leetcode
研究点啥好呢17 小时前
滴滴Go后端开发工程师面试题精选:10道高频考题+答案解析
java·开发语言·golang
承渊政道17 小时前
【动态规划算法】(两个数组的DP问题深度剖析与求解方法)
数据结构·c++·学习·算法·leetcode·动态规划·哈希算法
加农炮手Jinx17 小时前
LeetCode 26. Remove Duplicates from Sorted Array 题解
算法·leetcode·力扣