Tree - 109. Convert Sorted List to Binary Search Tree

41

109. Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted linked list: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

思路:

和108题一样都是把一些有序数据整理成bst,这里的数据结构是链表,做法和数组一样,找链表中点,用的都是快慢指针的办法,然后根据root分开成两个链表之后继续递归求解左右子树。

代码:

go:

/**

 * 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 sortedListToBST(head *ListNode) *TreeNode {
    if head == nil {
        return nil
    }
    
    if head.Next == nil {
        return &TreeNode{Val:head.Val}
    }
    
    
    mid := findMid(head)
    root :=  &TreeNode{Val:mid.Val}
    
    root.Left = sortedListToBST(head)
    root.Right = sortedListToBST(mid.Next)
    
    return root 
    
}

// find list mid
func findMid(head *ListNode) *ListNode {
	var prev *ListNode
	slow, fast :=  head, head
    for fast != nil && fast.Next != nil {
        prev = slow
        slow = slow.Next
        fast = fast.Next.Next
    }
    prev.Next = nil // partition list
    return slow
}