I tried solving a challenge that asks for the diameter of a tree (not necessarily a binary tree) in python 3.0. The challenge is actually to find the "circumference" of a tree, which is basically the diameter of a tree (length of the longest path) multiplied by 3.
I created a adjacency list and ran depth-first search (DFS) on the tree, storing the greatest two heights of the sub-trees, and the maximum diameter encountered so far. I think my logic is pretty correct, but I can't seem to find a problem with the code.
The codeforces compiler gave this error:
"memory limit exceeded on test case 1" for PyPy 3.6
"Runtime error on test case 4" for Python 3.7
But I could not find any test case myself for which the code produced an error.
Problem reference: https://codeforces.com/gym/102694/problem/A
My code:
import sys,math
sys.setrecursionlimit(10**7)
def get_int(): # returns a list of integers after taking an input
return list(map(int,sys.stdin.readline().strip().split()))
def dfs(adj_list,u):
global visited
d,h=0,[0,0] #Diameter, Maximum two heights.
# print(u)
if adj_list[u]==[]:
# print(0,0)
return 0,0
else:
for v in adj_list[u]:
if visited[v]==True:
continue
else:
visited[v]=True
tmp_d,tmp_h=dfs(adj_list,v)
d=max(d,tmp_d)
tmp_h+=1
if tmp_h>h[1]:
if tmp_h>h[0]:
h[1],h[0]=h[0],h[1]
h[0]=tmp_h
else:
h[1]=tmp_h
d=max(h[0]+h[1],d)
# print(d,h[0])
return d,h[0]
if __name__ == "__main__":
N=int(input().strip())
adj_list=[[] for _ in range(N+1)] #Stores the adjacency list
adj_list[0]=None
root=1
for _ in range(N-1):
a,b=get_int()
adj_list[a].append(b)
adj_list[b].append(a)
visited=[False]*(N+1)
visited[1]=True
print(3*dfs(adj_list,root)[0])