-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path108.将有序数组转换为二叉搜索树.py
More file actions
59 lines (56 loc) · 1.44 KB
/
108.将有序数组转换为二叉搜索树.py
File metadata and controls
59 lines (56 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#
# @lc app=leetcode.cn id=108 lang=python
#
# [108] 将有序数组转换为二叉搜索树
#
# https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/description/
#
# algorithms
# Easy (67.32%)
# Likes: 255
# Dislikes: 0
# Total Accepted: 34.2K
# Total Submissions: 50.8K
# Testcase Example: '[-10,-3,0,5,9]'
#
# 将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
#
# 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
#
# 示例:
#
# 给定有序数组: [-10,-3,0,5,9],
#
# 一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:
#
# 0
# / \
# -3 9
# / /
# -10 5
#
#
#
# @lc code=start
# 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 sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
def helper(nums,l,r):
if r<l:
return None
mid=int(l+(r-l)/2)
root=TreeNode(nums[mid])
root.left=helper(nums,l,mid-1)
root.right=helper(nums,mid+1,r)
return root
return helper(nums,0,len(nums)-1) if nums else None
# @lc code=end