My code works with small binary tree but with big ones (around 10000 nodes) it takes 15 sec to process.
For small binary tree I'm always getting correct answer and it is fast.
How can I make my program faster for big binary tree?
(x, y) is a neighbour pair when the depth of x and y is the same, the node color of x and y is the same, the node key of x and y are equal and there is no other node of the same node color between x and y on the horizontal line connecting x and y in standard drawing..
Input
The first line of input contains number of nodes and root node. Next, each line describes each node.
The first value is the node label, the second value is the node key, the third and the fourth values represent the labels of the left and right child respectively, and the fifth value represents the node color, white is 0, black is 1. If any of the children does not exist there is value 0 instead of the child label at the corresponding place
Output
number of neighbour pairs in the input tree
My code
from collections import defaultdict
def read_input(inputstring):
inputs = inputstring.split(" ")
nodes_number = int(inputs[0])
root_node = int(inputs[1])
input_tree = [list(map(int, input().split())) for _ in range(nodes_number)]
tree = {}
result = {}
def depth(node, count):
for i in input_tree:
node_label = i[0]
if node_label == node:
tree.setdefault(count, []).append(i)
l_node, r_node = i[2], i[3]
if l_node != 0 and r_node != 0:
depth(l_node, count+1)
depth(r_node, count+1)
elif l_node != 0:
depth(l_node, count+1)
elif r_node != 0:
depth(r_node, count+1)
depth(root_node, 0)
def neighbour_pair(input_tree):
for value in input_tree.values():
for i in range(len(value)):
for j in range(len(value)):
if j > i:
if value[i][1] == value[j][1] and value[i][4] == value[j][4]:
result.setdefault(value[i][0], []).append(value[j][0])
neighbour_pair(tree)
return len(result)
if __name__ == '__main__':
print(read_input(input()))
Example of small input
13 5
7 50 0 0 1
2 70 10 11 0
4 30 9 0 0
6 70 0 0 0
1 90 8 12 0
9 90 0 2 1
13 90 0 6 0
5 30 4 3 0
12 80 0 0 1
10 50 0 0 1
11 50 0 0 0
3 80 1 13 0
8 70 7 0 1
Its associated representation:
The labels are written in the yellow rectangle at the corresponding nodes. Their key is the number in the black or white oval. For this example, the neighbour pairs are (1, 13), (2, 6), (10, 7)
.
As such, the output of the program for this tree is:
3