问题描述
关于二进制搜索树,我一直试图绕过递归 但是,我没有运气。 有人可以用最简单的形式向我解释此代码块(此问题已广泛使用)如何将数组转换为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。此外,如果不考虑这种情况并中断递归,该算法肯定会陷入无限递归中。