題目
原題頁面:https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
題目型別:Tree, Depth-first Search
難度評價:Medium
類似題目:(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.
分析
用遞迴的方法,每次選擇當前子序列的中點作為子樹的root,然後再遞迴對左邊子序列和右邊子序列進行處理。
原題中標註為深度搜索DFS。這裡是構建二叉樹,構建的順序類似於二叉樹的先序遍歷。由於樹是一種特殊的圖,因此二叉樹的先序遍歷其實就是圖的DFS,而層次遍歷就是圖的BFS。
程式碼
1 | class Solution: |
本文地址:https://xnerv.wang/zh-tw/leetcode-convert-sorted-array-to-binary-search-tree/
