微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

阵列到BST基本案例

如何解决阵列到BST基本案例

关于二进制搜索树,我一直试图绕过递归 但是,我没有运气。 有人可以用最简单的形式向我解释此代码块(此问题已广泛使用)如何将数组转换为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)

在此问题上的任何帮助将是巨大的!谢谢

解决方法

helper(i,j)用于将array[i:j+1]转换为BST。

def helper(left,right):
            # base case
            if left > right:
                return None`

此基本情况很重要,因为如果左索引大于右索引,则从逻辑上讲不可能为此创建BST。此外,如果不考虑这种情况并中断递归,该算法肯定会陷入无限递归中。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。