Convert Sorted List to Binary Search Tree Solutions in Go
Number 109
Difficulty Medium
Acceptance 47.8%
Link LeetCode
Other languages C++
Solutions
Go solution by halfrost/LeetCode-Go
package leetcodeimport ("github.com/halfrost/LeetCode-Go/structures")// ListNode definetype ListNode = structures.ListNode/*** Definition for singly-linked list.* type ListNode struct {* Val int* Next *ListNode* }*/// TreeNode definetype TreeNode = structures.TreeNode/*** Definition for a binary tree node.* type TreeNode struct {* Val int* Left *TreeNode* Right *TreeNode* }*/func sortedListToBST(head *ListNode) *TreeNode {if head == nil {return nil}if head != nil && head.Next == nil {return &TreeNode{Val: head.Val, Left: nil, Right: nil}}middleNode, preNode := middleNodeAndPreNode(head)if middleNode == nil {return nil}if preNode != nil {preNode.Next = nil}if middleNode == head {head = nil}return &TreeNode{Val: middleNode.Val, Left: sortedListToBST(head), Right: sortedListToBST(middleNode.Next)}}func middleNodeAndPreNode(head *ListNode) (middle *ListNode, pre *ListNode) {if head == nil || head.Next == nil {return nil, head}p1 := headp2 := headfor p2.Next != nil && p2.Next.Next != nil {pre = p1p1 = p1.Nextp2 = p2.Next.Next}return p1, pre}