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
}
相关推荐
Pniubi11 小时前
力扣54.螺旋矩阵
算法·leetcode·矩阵
利威尔xu1 天前
Go map 底层崩溃:3 个 goroutine 并发写同一张 map,fatal error 崩掉整个服务
golang·源码·map·并发·后端开发
Rain的Java大神之路1 天前
LeetCode 37 解数独面试攻略:回溯 + 位掩码 + MRV,从暴力到毫秒级求解
java·后端·leetcode
Pniubi1 天前
力扣73 矩阵置零
算法·leetcode·矩阵
文丑颜不良啊2 天前
LeetCode2261~2280题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2241~2260题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2321~2340题目解析
java·leetcode
利威尔xu2 天前
2026-11-08-Go-defer-panic-recover面试
面试·golang
文丑颜不良啊3 天前
LeetCode2221~2240题目解析
java·leetcode
Navigator_Z3 天前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode