我一直在嘗試解決有關(guān)二叉搜索樹的遞歸問(wèn)題,但是我沒(méi)有運(yùn)氣。有人可以用最簡(jiǎn)單的形式向我解釋一下這段代碼(在這個(gè)問(wèn)題中廣泛使用)如何將數(shù)組轉(zhuǎn)換為 BST:def helper(left, right): # base case if left > right: return None整個(gè)代碼(取自leetcode https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/discuss/900790/Python3-with-explanation-faster-than-100-PreOrder-traversal)def sortedArrayToBST(self, nums: List[int]) -> TreeNode: # statrt with the middle element and for the right ones go tree.right and for the left ones go tree.left # would have to traverse once so the time complexity will be O(n). def helper(left, right): # base case if left > right: return None # get the length to the nearest whole number length = (left + right) // 2 # preOrder traversal root = TreeNode(nums[length]) root.left = helper(left , length -1) root.right = helper(length+1, right) return root return helper(0 , len(nums) - 1)對(duì)此事的任何幫助都會(huì)很棒!謝謝
1 回答

慕尼黑的夜晚無(wú)繁華
TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超6個(gè)贊
helper(i,j)用于轉(zhuǎn)換array[i:j+1]為 BST。
def helper(left, right):
# base case
if left > right:
return None`
這個(gè)基本情況很重要,因?yàn)槿绻笏饕笥谟宜饕敲催壿嬌暇筒豢赡転榇藙?chuàng)建 BST。此外,如果我們不考慮這種情況并中斷遞歸,算法肯定會(huì)陷入無(wú)限遞歸。
添加回答
舉報(bào)
0/150
提交
取消