Skip to content

Commit 101ea31

Browse files
author
shiv
committed
count BST nodes within a range
1 parent c941258 commit 101ea31

File tree

3 files changed

+56
-5
lines changed

3 files changed

+56
-5
lines changed

.node_connecting.py.swp

-12 KB
Binary file not shown.

count_bst_nodes.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# Shiv's code for counting BST nodes
2+
3+
'''
4+
1
5+
6
6+
10 5 50 1 40 100
7+
5 45
8+
'''
9+
10+
tn = int(input())
11+
12+
class Node:
13+
def __init__(self, name):
14+
self.name=name
15+
self.l=None
16+
self.r=None
17+
18+
def build_tree(root, node):
19+
if node>=root.name:
20+
if root.r == None:
21+
root.r = Node(node)
22+
else:
23+
build_tree(root.r, node)
24+
elif node < root.name:
25+
if root.l == None:
26+
root.l = Node(node)
27+
else:
28+
build_tree(root.l, node)
29+
30+
node_count = 0
31+
32+
def getCountOfNode(root, l, h):
33+
global node_count
34+
if l <= root.name <= h:
35+
node_count+=1
36+
if root.l != None:
37+
getCountOfNode(root.l, l, h)
38+
if root.r !=None:
39+
getCountOfNode(root.r, l, h)
40+
41+
42+
for i in range(tn):
43+
node_count = 0
44+
n = int(input())
45+
nodes = list(map(int, input().split()))
46+
l, h = list(map(int, input().split()))
47+
root = Node(nodes[0])
48+
for node in nodes[1:]:
49+
build_tree(root, node)
50+
getCountOfNode(root,l,h)
51+
print(node_count)
52+

ip.txt

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
2
2-
2
3-
3 1 L 3 2 R
4-
4
5-
10 20 L 10 30 R 20 40 L 20 60 R
1+
1
2+
6
3+
10 5 50 1 40 100
4+
5 45

0 commit comments

Comments
 (0)