109. Convert Sorted List to Binary Search Tree
https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
js
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {ListNode} head
* @return {TreeNode}
*/
function sortedListToBST(head) {
const vals = []
while (head) {
vals.push(head.val)
head = head.next
}
function buildTree(nums, left, right) {
if (left > right) {
return null
}
const mid = (left + right + 1) / 2 >> 0
const root = new TreeNode(nums[mid])
root.left = buildTree(nums, left, mid - 1)
root.right = buildTree(nums, mid + 1, right)
return root
}
return buildTree(vals, 0, vals.length - 1)
}
py
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def sortedListToBST(self, head):
"""
:type head: ListNode
:rtype: TreeNode
"""
vals = []
while head:
vals.append(head.val)
head = head.next
return self.buildTree(vals, 0, len(vals) - 1)
def buildTree(self, nums, left, right):
if left > right:
return None
mid = (left + right + 1) // 2
root = TreeNode(nums[mid])
root.left = self.buildTree(nums, left, mid - 1)
root.right = self.buildTree(nums, mid + 1, right)
return 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 {
var vals []int
for head != nil {
vals = append(vals, head.Val)
head = head.Next
}
return buildTree(vals, 0, len(vals)-1)
}
func buildTree(nums []int, left, right int) *TreeNode {
if left > right {
return nil
}
sum := left + right
mid := 0
if sum%2 == 0 {
mid = sum / 2
} else {
mid = (sum + 1) / 2
}
root := &TreeNode{Val: nums[mid]}
root.Left = buildTree(nums, left, mid-1)
root.Right = buildTree(nums, mid+1, right)
return root
}