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 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-convert-sorted-array-to-binary-search-tree/
