Skip to content

Commit 6f12319

Browse files
author
Amogh Singhal
authored
Update bst_nodes_in_range.py
1 parent 8b84002 commit 6f12319

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

bst_nodes_in_range.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,21 @@ def __init__(self, data):
1111

1212
def nodesWithinRange(root, range):
1313
low, high = range
14+
# this is the base case
1415
if root is None:
1516
return 0
17+
# optional: to improve efficiency
18+
elif root.data == high or root.data == low:
19+
return 1
20+
# if the current node lies in the range
1621
elif root.data <= high and root.data >= low:
1722
return (
1823
1 + nodesWithinRange(root.left, range) + nodesWithinRange(root.right, range)
1924
)
20-
elif root.data == high or root.data == low:
21-
return 1
25+
# if the current node lies in left subtree
2226
elif root.data > high:
2327
return nodesWithinRange(root.left, range)
28+
# if the current node lies in the right subtree
2429
elif root.data < low:
2530
return nodesWithinRange(root.right, range)
2631

0 commit comments

Comments
 (0)