'RecursionError: maximum recursion depth exceeded in comparison : Recursive function
i dont understand why am getting this max depth error . iam trying to find index of number in array using bst recursive approach , below is my code
# Binary Search Tree using recursion
def search(arr,target,s,e):
middle = s + (e - s) // 2
if s > e:
return -1
if target == arr[middle]:
return middle
if target < arr[middle]:
return search(arr,target,s,middle-1)
return search(arr,target,s,middle+1)
ARR = [1,2,3,4,5,6,7,8,9,10]
k = search(ARR,9,0,len(ARR) - 1)
print(k)
can anyone tell me whats happening in the code block
error block:
PS C:\Users\admin\Desktop\DSA> & C:/Users/admin/AppData/Local/Programs/Python/Python310/python.exe c:/Users/admin/Desktop/DSA/recursion/bst.py Traceback (most recent call last): File "c:\Users\admin\Desktop\DSA\recursion\bst.py", line 20, in k = search(ARR,9,0,len(ARR) - 1) File "c:\Users\admin\Desktop\DSA\recursion\bst.py", line 16, in search
return search(arr,target,s,middle+1) File "c:\Users\admin\Desktop\DSA\recursion\bst.py", line 16, in search
return search(arr,target,s,middle+1) File "c:\Users\admin\Desktop\DSA\recursion\bst.py", line 16, in search
return search(arr,target,s,middle+1) [Previous line repeated 995 more times] File "c:\Users\admin\Desktop\DSA\recursion\bst.py", line 7, in search
if s > e: RecursionError: maximum recursion depth exceeded in comparison
Solution 1:[1]
The last case should be search(arr,target,middle,e)
.
The way you have it coded, it always searches the first half of the array, and eventually you reach the recursion limit.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | John Gordon |