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
}
相关推荐
Dream it possible!30 分钟前
LeetCode 面试经典 150_栈_简化路径(53_71_C++_中等)(栈+stringstream)
c++·leetcode·面试·
程序员阿鹏39 分钟前
49.字母异位词分组
java·开发语言·leetcode
Espresso Macchiato1 小时前
Leetcode 3715. Sum of Perfect Square Ancestors
算法·leetcode·职场和发展·leetcode hard·树的遍历·leetcode 3715·leetcode周赛471
星星点点洲4 小时前
PostgreSQL 15二进制文件
开发语言·设计模式·golang
Miraitowa_cheems8 小时前
LeetCode算法日记 - Day 73: 最小路径和、地下城游戏
数据结构·算法·leetcode·职场和发展·深度优先·动态规划·推荐算法
野蛮人6号8 小时前
力扣热题100道之560和位K的子数组
数据结构·算法·leetcode
Swift社区9 小时前
LeetCode 400 - 第 N 位数字
算法·leetcode·职场和发展
剪一朵云爱着10 小时前
力扣2080. 区间内查询数字的频率
算法·leetcode
youliroam10 小时前
成语接龙学习
学习·golang·uniapp·成语接龙
Dream it possible!10 小时前
LeetCode 面试经典 150_栈_有效的括号(52_20_C++_简单)(栈+哈希表)
c++·leetcode·面试··哈希表