简繁EN

LeetCodeNo. 118

[LeetCode with Python] 108. Convert Sorted Array to Binary Search Tree

Contents

Problem

Problem page: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
Topics: Tree, Depth-first Search
Difficulty: Medium
Similar problems: (M) Convert Sorted List to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.


Analysis

Use recursion. At each step, pick the middle element of the current subsequence as the root of the subtree. Then recursively process the left and right subsequences.
The original problem is tagged as depth-first search (DFS). Here we're building a binary tree, and the order we build it in is like a preorder traversal. Since a tree is a special kind of graph, a preorder traversal of a binary tree is a DFS of the graph, and a level-order traversal is a breadth-first search (BFS) of the graph.


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:

def doSortedArrayToBST(self, num, start, end):
if start > end:
return None
mid = start + (end - start) / 2
root = TreeNode(num[mid])
root.left = self.doSortedArrayToBST(num, start, mid - 1)
root.right = self.doSortedArrayToBST(num, mid + 1, end)
return root

# @param num, a list of integers
# @return a tree node
def sortedArrayToBST(self, num):
len_num = len(num)
if 0 == len_num:
return None
return self.doSortedArrayToBST(num, 0, len_num - 1)

Article link: https://xnerv.wang/en/leetcode-convert-sorted-array-to-binary-search-tree/