题目:
给定一个单链表的头节点 head ,其中的元素 按升序排序 ,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差不超过 1。
算法:
注意findMid函数中,head == afterTail的边界条件处理
func sortedListToBST(head *ListNode) *TreeNode {
return convertToBST(head, nil)
}
func convertToBST(head, afterTail *ListNode) *TreeNode {
if head == nil {
return nil
}
if head.Next == afterTail {
return &TreeNode{Val: head.Val}
}
mid := findMid(head, afterTail)
if mid == nil {
return nil
}
// fmt.Println(head.Val, mid.Val)
node := &TreeNode{Val: mid.Val}
node.Left = convertToBST(head, mid)
node.Right = convertToBST(mid.Next, afterTail)
return node
}
func findMid(head, afterTail *ListNode) *ListNode {
if head == nil || head == afterTail {
return nil
}
if head.Next == afterTail{
return head
}
slow, fast := head, head
for fast != afterTail && fast.Next != afterTail {
fast = fast.Next.Next
slow = slow.Next
}
return slow
}