Skip to content

Commit 4e773e8

Browse files
author
weiy
committed
convert sorted array to binary search tree easy
1 parent e35d04b commit 4e773e8

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
"""
2+
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
3+
4+
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.
5+
6+
Example:
7+
8+
Given the sorted array: [-10,-3,0,5,9],
9+
10+
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
11+
12+
0
13+
/ \
14+
-3 9
15+
/ /
16+
-10 5
17+
18+
19+
给定一个已排序过的数组,将它转换为一颗高度平衡的二叉搜索树。
20+
21+
也就是两颗子树的高度差不超过1。
22+
23+
因为是排序的数组,相对来说也异常简单,可以将它看做是一颗二叉搜索树中序遍历后的结果。
24+
按照此结果转换回去就是了。
25+
26+
27+
每次都二分:
28+
29+
[-10,-3,0,5,9]
30+
mid
31+
5//2 = 2 mid = 2
32+
0
33+
[-10, -3] [5, 9] 2 // 2 = 1 mid = 1
34+
↓ ↓
35+
-3 9
36+
[-10] [] [5] []
37+
38+
为空则不进行下面的操作。
39+
40+
beat 98%
41+
42+
测试地址:
43+
https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/
44+
45+
"""
46+
# Definition for a binary tree node.
47+
# class TreeNode(object):
48+
# def __init__(self, x):
49+
# self.val = x
50+
# self.left = None
51+
# self.right = None
52+
53+
class Solution(object):
54+
def sortedArrayToBST(self, nums):
55+
"""
56+
:type nums: List[int]
57+
:rtype: TreeNode
58+
"""
59+
if not nums:
60+
return None
61+
62+
def makeBinarySearchTree(nums):
63+
mid = len(nums) // 2
64+
65+
root = TreeNode(nums[mid])
66+
left = nums[:mid]
67+
right = nums[mid+1:]
68+
69+
if left:
70+
root.left = makeBinarySearchTree(left)
71+
if right:
72+
root.right = makeBinarySearchTree(right)
73+
74+
return root
75+
76+
root = makeBinarySearchTree(nums)
77+
return root
78+

0 commit comments

Comments
 (0)