Skip to content

Commit 433721f

Browse files
author
Amogh Singhal
authored
Update bst_nodes_in_range.py
1 parent f66b82b commit 433721f

File tree

1 file changed

+17
-11
lines changed

1 file changed

+17
-11
lines changed

bst_nodes_in_range.py

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
1-
# Problem: Find the no. of nodes in a BST
2-
# that lies in a given range
1+
# Problem: Find the no. of nodes in a BST that lies in a given range
32

3+
# Algorithm: We will traverse the tree recursively until we encounter leaf nodes (Base case)
4+
# else we do the following
5+
# 1. Current node is less than the given range --> Traverse the right subtree
6+
# 2. Current node is more than the given range --> Traverse the left subtree
7+
# 3. Current node lies in the given range --> Increment Count; Traverse both the left and right subtree
48

9+
# Data Structure for Tree Node
510
class Node:
611
def __init__(self, data):
712
self.data = data
@@ -29,13 +34,14 @@ def nodesWithinRange(root, range):
2934
elif root.data < low:
3035
return nodesWithinRange(root.right, range)
3136

37+
if __name__ == "main":
38+
39+
node = Node(10)
40+
node.left = Node(5)
41+
node.left.left = Node(1)
42+
node.right = Node(50)
43+
node.right.left = Node(45)
44+
node.right.right = Node(100)
3245

33-
node = Node(10)
34-
node.left = Node(5)
35-
node.left.left = Node(1)
36-
node.right = Node(50)
37-
node.right.left = Node(45)
38-
node.right.right = Node(100)
39-
40-
result = nodesWithinRange(node, (5, 45))
41-
print(result)
46+
result = nodesWithinRange(node, (5, 45))
47+
print(result)

0 commit comments

Comments
 (0)