leetcode109有序链表转换二叉搜索树

leetcode109 Convert Sorted List to Binary Search Tree

Posted by BY on October 23, 2019

前言

中间又断更新。

正文

问题来源

本问题来自leetcode上的109题。

问题描述

给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

示例 1:

给定的有序链表: [-10, -3, 0, 5, 9],

一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:

      0
     / \
   -3   9
   /   /
 -10  5

分析:

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func createBST(si []int, start, end int) *TreeNode {
    if start > end {
        return nil
    }
    mid := (start + end) / 2 
    t := &TreeNode{}
    t.Val = si[mid]
    t.Left = createBST(si, start, mid-1)
    t.Right = createBST(si, mid+1, end)
    return t
}

func sortedListToBST(head *ListNode) *TreeNode {
    si := make([]int, 0, 20)
    for head != nil {
        si = append(si, head.Val)
        head = head.Next
    }
    return createBST(si, 0, len(si)-1)
}

快慢指针找到中间节点

func createBST(head, end *ListNode) *TreeNode {
    if head == end {
        return nil
    }
    slow, quick := head, head
    for quick != end {
        quick = quick.Next
        if quick != end {
            slow = slow.Next
            quick = quick.Next
        }        
    }
    t := &TreeNode{}
    t.Val = slow.Val
    t.Left = createBST(head, slow)
    t.Right = createBST(slow.Next, end)
    return t
}

func sortedListToBST(head *ListNode) *TreeNode {
    return createBST(head, nil)
}

总结:

勤思考。

结语

不管怎么样好好加油。