本文主要是介绍Golang | Leetcode Golang题解之第109题有序链表转换二叉搜索树,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
题解:
var globalHead *ListNodefunc sortedListToBST(head *ListNode) *TreeNode {globalHead = headlength := getLength(head)return buildTree(0, length - 1)
}func getLength(head *ListNode) int {ret := 0for ; head != nil; head = head.Next {ret++}return ret
}func buildTree(left, right int) *TreeNode {if left > right {return nil}mid := (left + right + 1) / 2root := &TreeNode{}root.Left = buildTree(left, mid - 1)root.Val = globalHead.ValglobalHead = globalHead.Nextroot.Right = buildTree(mid + 1, right)return root
}
这篇关于Golang | Leetcode Golang题解之第109题有序链表转换二叉搜索树的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!