有序链表转换二叉搜索树
/**
* 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 {
var nodes []ListNode
for head !=nil {
nodes= append(nodes,*head)
head = head.Next
}
return builder(nodes,0,len(nodes)-1)
}
func builder(nodes []ListNode,left,right int)*TreeNode{
if left >right {
return nil
}
mid :=(left+right+1)/2
root :=&TreeNode{nodes[mid].Val,nil,nil}
root.Left = builder(nodes,left,mid-1)
root.Right = builder(nodes,mid+1,right)
return root
}