原题
https://leetcode.cn/problems/convert-sorted-list-to-binary-search-tree/description/
思路
遍历 + 递归
复杂度
时间:O(n)
空间:O(n)
Python代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
l = []
while head:
l.append(head.val)
head = head.next
# 将列表转为二叉搜索树
def helper(l):
if len(l) == 0:
return None
idx = len(l) // 2
root = TreeNode(l[idx])
root.left = helper(l[:idx])
root.right = helper(l[idx+1:])
return root
return helper(l)
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 {
l := []int{}
for head != nil {
l = append(l, head.Val)
head = head.Next
}
// 将切片转为二叉搜索树
var helper func([]int) *TreeNode
helper = func(l []int) *TreeNode {
if len(l) == 0 {
return nil
}
idx := len(l) / 2
root := &TreeNode{Val: l[idx]}
root.Left = helper(l[:idx])
root.Right = helper(l[idx+1:])
return root
}
return helper(l)
}
570

被折叠的 条评论
为什么被折叠?



