Can't do DFS with python?

Code shows error for a tree with 200000 nodes(in a straight line)
Error shown: Exit code is -1073741571

Does anyone have some solution for this???

import sys
input = sys.stdin.readline
sys.setrecursionlimit(200007)

def solve(g,x,li,vis):         # g is a graph/tree,  vis is array to ckeck visisted nodes
    vis[x]=1                   # li has length 1
    print(x)

    if len(g[x])==1:
        li[0]+=1
        return 1

    bol=0
    for y in g[x]:
        if not (vis[y]): bol+=solve(g,y,li,vis)

    if bol>0: bol=0
    else: bol=1
    li[0]+=bol
    return bol




t=int(input())

for _ in range(t):
    n=int(input())

    g=[[] for i in range(n+1)]


    for i in range(n-1):
        u,v=map(int,input().split())
        g[u].append(v)
        g[v].append(u)

    vis=[0]*(n+1)

    x=0
    li=[0]
    vis[1]=1
    for i in g[1]:
        x+=solve(g,i,li,vis)

    l=li[0]
    b=n-l-1

    if x==0: print(l-b+1)
    else: print(l-b)

Please either format your code or (better!) link to your submission - the forum software has mangled it and it won’t compile! :slight_smile:

Done formatting my code. (Earlier I thought ``` was same as β€˜β€™β€™. This resulted in my code not being formatted)

1 Like

Can we get a link to the question?

Maybe this would help.

1 Like