亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

數組到 BST 基本情況

數組到 BST 基本情況

猛跑小豬 2023-12-08 17:04:52
我一直在嘗試解決有關二叉搜索樹的遞歸問題,但是我沒有運氣。有人可以用最簡單的形式向我解釋一下這段代碼(在這個問題中廣泛使用)如何將數組轉換為 BST:def helper(left, right):            # base case            if left > right:                return None整個代碼(取自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)對此事的任何幫助都會很棒!謝謝
查看完整描述

1 回答

?
慕尼黑的夜晚無繁華

TA貢獻1864條經驗 獲得超6個贊

helper(i,j)用于轉換array[i:j+1]為 BST。


def helper(left, right):

            # base case

            if left > right:

                return None`

這個基本情況很重要,因為如果左索引大于右索引,那么邏輯上就不可能為此創建 BST。此外,如果我們不考慮這種情況并中斷遞歸,算法肯定會陷入無限遞歸。


查看完整回答
反對 回復 2023-12-08
  • 1 回答
  • 0 關注
  • 151 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號