|
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 |
3 | 2 |
|
| 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 |
4 | 8 |
|
| 9 | +# Data Structure for Tree Node |
5 | 10 | class Node:
|
6 | 11 | def __init__(self, data):
|
7 | 12 | self.data = data
|
@@ -29,13 +34,14 @@ def nodesWithinRange(root, range):
|
29 | 34 | elif root.data < low:
|
30 | 35 | return nodesWithinRange(root.right, range)
|
31 | 36 |
|
| 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) |
32 | 45 |
|
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