Problem:
 Score : 600 points    Problem Statement  We have a tree with N vertices numbered 1 to N . The i -th edge in this tree connects Vertex a_i and b_i .
For each k=1, ..., N , solve the problem below:   Consider writing a number on each vertex in the tree in the following manner:  First, write 1 on Vertex k .  Then, for each of the numbers 2, ..., N in this order, write the number on the vertex chosen as follows:  Choose a vertex that still does not have a number written on it and is adjacent to a vertex with a number already written on it. If there are multiple such vertices, choose one of them at random.      Find the number of ways in which we can write the numbers on the vertices, modulo (10^9+7) .       Constraints   2 \leq N \leq 2 \times 10^5  1 \leq a_i,b_i \leq N  The given graph is a tree.         Input  Input is given from Standard Input in the following format:  N  a_1  b_1  :  a_{N-1}  b_{N-1}       Output  For each k=1, 2, ..., N in this order, print a line containing the answer to the problem.        Sample Input 1 3
1 2
1 3      Sample Output 1 2
1
1  The graph in this input is as follows:   For k=1 , there are two ways in which we can write the numbers on the vertices, as follows:   Writing 1, 2, 3 on Vertex 1, 2, 3 , respectively  Writing 1, 3, 2 on Vertex 1, 2, 3 , respectively        Sample Input 2 2
1 2      Sample Output 2 1
1  The graph in this input is as follows:        Sample Input 3 5
1 2
2 3
3 4
3 5      Sample Output 3 2
8
12
3
3  The graph in this input is as follows:        Sample Input 4 8
1 2
2 3
3 4
3 5
3 6
6 7
6 8      Sample Output 4 40
280
840
120
120
504
72
72  The graph in this input is as follows:

Solution (Python):

import sys
sys.setrecursionlimit(10**7) 
import math



from functools import lru_cache



def input(): return sys.stdin.readline()[:-1]
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]

        
class comb:
    def __init__(self,N,mod=10**9+7):
        self.mod=mod
        self.fact=[0]*(N+1)
        self.ifact=[0]*(N+1)
        fact,ifact=self.fact,self.ifact
        fact[0],fact[1],ifact[0],ifact[1]=1,1,1,1
        for i in range(2,N+1):
            x=(fact[i-1]*i)%mod
            fact[i]=x
            ifact[i]=self.extgcd1(x,mod)
        

    
    def extgcd1(self,a0,b0):
        u,v,a,b=1,0,a0,b0
        while b:
            t,a=divmod(a,b)
            a,b,u,v=b,a,v,u-t*v
        if a!=1: 
            print("not 素")
            return -1
        return u%b0

    
    def comb(self,n,r): return (self.fact[n]*self.ifact[r]%self.mod)*self.ifact[n-r]%self.mod

    @lru_cache(maxsize = None)
    def mulcomb(self,n,*rs):
        ans=self.fact[n]
        for r in rs: ans=(ans*self.ifact[r])%self.mod
        return ans

class rerooting:
    def __init__(self,N,edge):
        
        self.unit=(1,0)
        self.mod=10**9+7
        self.edge=edge
        self.cb=comb(N)
        self.fact=self.cb.fact
        self.ifact=self.cb.ifact
        self.par=[-1]*N
        self.N=N
        self.visited=[0]*N
        self.dics=[dict() for _ in range(N)]
        self.ikigake=[]
        self.tot=[self.unit]*N
    
    
    def func(self,x,y):
        
        
        p1,s1=x
        p2,s2=y
        ans=(p1*p2)%self.mod
        ssum=s1+s2
        ans*=self.cb.comb(ssum,s1)
        
        ans%=self.mod
        return ans,ssum 

    def addnode(self,x):
        return x[0],x[1]+1

    def _dfs(self,e,pa):
        edge=self.edge
        self.par[e]=pa
        self.ikigake.append(e)
        ans=self.unit
        for ne in edge[e]:
            if self.par[ne]!=-1:
                continue
            ans=self.func(ans,self.addnode(self._dfs(ne,e)))
            
        if pa!=e:
            self.dics[pa][e]=ans
        
        return ans
    
    def forward(self,start):
        self._dfs(start,start)
        
        
        for e in self.ikigake:
            pa=self.par[e]
            de=self.dics[e]
            nes=tuple(de.keys())
            nvals=tuple(de.values())
            l=len(nes)
            aleft=[self.unit]
            aright=[self.unit]
            cleft=self.unit
            cright=self.unit
            for i in range(l-1):
                aleft.append(self.func(aleft[-1],self.addnode(nvals[i])))
                aright.append(self.func(aright[-1],self.addnode(nvals[-i-1])))
                
            self.tot[e]=self.func(aright[-1],self.addnode(nvals[0]))
            for i,ne in enumerate(nes):
                if ne==pa:
                    continue
                self.dics[ne][e]=self.func(aleft[i],aright[-1-i])
                
        

def main():
    mod = 1000000007
    

    N = int(input())
    
    
    
    

    def tree_init(N):
        edgelist = [[] for _ in range(N)]
        elist=set()
        for a, b in [map(int, input().split()) for i in range(N-1)]:
            edgelist[a-1].append(b-1)
            edgelist[b-1].append(a-1)
            elist.add((a-1,b-1))
        return edgelist,elist

    edge,elist=tree_init(N)
    cb=comb(N)
    rt=rerooting(N,edge)
    rt.forward(0)

    for a in range(N):
        print(rt.tot[a][0])

if __name__ == "__main__":
    main()

Solution (Python):

import sys
sys.setrecursionlimit(10**7) 
import math



from functools import lru_cache



def input(): return sys.stdin.readline()[:-1]
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]

        
class comb:
    def __init__(self,N,mod=10**9+7):
        self.mod=mod
        self.fact=[0]*(N+1)
        self.ifact=[0]*(N+1)
        fact,ifact=self.fact,self.ifact
        fact[0],fact[1],ifact[0],ifact[1]=1,1,1,1
        for i in range(2,N+1):
            x=(fact[i-1]*i)%mod
            fact[i]=x
            ifact[i]=self.extgcd1(x,mod)
        

    @lru_cache(maxsize = None)
    def extgcd1(self,a0,b0):
        u,v,a,b=1,0,a0,b0
        while b:
            t,a=divmod(a,b)
            a,b,u,v=b,a,v,u-t*v
        if a!=1: 
            print("not 素")
            return -1
        return u%b0

    
    def comb(self,n,r): return (self.fact[n]*self.ifact[r]%self.mod)*self.ifact[n-r]%self.mod

    @lru_cache(maxsize = None)
    def mulcomb(self,n,*rs):
        ans=self.fact[n]
        for r in rs: ans=(ans*self.ifact[r])%self.mod
        return ans

class rerooting:
    def __init__(self,N,edge):
        
        self.unit=(1,0)
        self.mod=10**9+7
        self.edge=edge
        self.cb=comb(N)
        self.fact=self.cb.fact
        self.ifact=self.cb.ifact
        self.par=[-1]*N
        self.N=N
        self.visited=[0]*N
        self.dics=[dict() for _ in range(N)]
        self.ikigake=[]
        self.tot=[self.unit]*N
    
    
    def func(self,x,y):
        
        
        p1,s1=x
        p2,s2=y
        ans=(p1*p2)%self.mod
        ssum=s1+s2
        ans*=self.cb.comb(ssum,s1)
        
        ans%=self.mod
        return ans,ssum 

    def addnode(self,x):
        return x[0],x[1]+1

    def _dfs(self,e,pa):
        edge=self.edge
        self.par[e]=pa
        self.ikigake.append(e)
        ans=self.unit
        for ne in edge[e]:
            if self.par[ne]!=-1:
                continue
            ans=self.func(ans,self.addnode(self._dfs(ne,e)))
            
        if pa!=e:
            self.dics[pa][e]=ans
        
        return ans
    
    def forward(self,start):
        self._dfs(start,start)
        
        
        for e in self.ikigake:
            pa=self.par[e]
            de=self.dics[e]
            nes=tuple(de.keys())
            nvals=tuple(de.values())
            l=len(nes)
            aleft=[self.unit]
            aright=[self.unit]
            cleft=self.unit
            cright=self.unit
            for i in range(l-1):
                aleft.append(self.func(aleft[-1],self.addnode(nvals[i])))
                aright.append(self.func(aright[-1],self.addnode(nvals[-i-1])))
                
            self.tot[e]=self.func(aright[-1],self.addnode(nvals[0]))
            for i,ne in enumerate(nes):
                if ne==pa:
                    continue
                self.dics[ne][e]=self.func(aleft[i],aright[-1-i])
                
        

def main():
    mod = 1000000007
    

    N = int(input())
    
    
    
    

    def tree_init(N):
        edgelist = [[] for _ in range(N)]
        elist=set()
        for a, b in [map(int, input().split()) for i in range(N-1)]:
            edgelist[a-1].append(b-1)
            edgelist[b-1].append(a-1)
            elist.add((a-1,b-1))
        return edgelist,elist

    edge,elist=tree_init(N)
    cb=comb(N)
    rt=rerooting(N,edge)
    rt.forward(0)

    for a in range(N):
        print(rt.tot[a][0])

if __name__ == "__main__":
    main()

Solution (Python):

import sys
sys.setrecursionlimit(10**7) 
import math



from functools import lru_cache



def input(): return sys.stdin.readline()[:-1]
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]

        
class comb:
    def __init__(self,N,mod=10**9+7):
        self.mod=mod
        self.fact=[0]*(N+1)
        self.ifact=[0]*(N+1)
        fact,ifact=self.fact,self.ifact
        fact[0],fact[1],ifact[0],ifact[1]=1,1,1,1
        for i in range(2,N+1):
            x=(fact[i-1]*i)%mod
            fact[i]=x
            ifact[i]=self.extgcd1(x,mod)
        

    @lru_cache(maxsize = None)
    def extgcd1(self,a0,b0):
        u,v,a,b=1,0,a0,b0
        while b:
            t,a=divmod(a,b)
            a,b,u,v=b,a,v,u-t*v
        if a!=1: 
            print("not 素")
            return -1
        return u%b0

    @lru_cache(maxsize = None)
    def comb(self,n,r): return (self.fact[n]*self.ifact[r]%self.mod)*self.ifact[n-r]%self.mod

    @lru_cache(maxsize = None)
    def mulcomb(self,n,*rs):
        ans=self.fact[n]
        for r in rs: ans=(ans*self.ifact[r])%self.mod
        return ans

class rerooting:
    def __init__(self,N,edge):
        
        self.unit=(1,0)
        self.mod=10**9+7
        self.edge=edge
        cb=comb(N)
        self.fact=cb.fact
        self.ifact=cb.ifact
        self.par=[-1]*N
        self.N=N
        self.visited=[0]*N
        self.dics=[dict() for _ in range(N)]
        self.ikigake=[]
        self.tot=[self.unit]*N
    
    
    def func(self,x,y):
        
        
        p1,s1=x
        p2,s2=y
        ans=(p1*p2)%self.mod
        ssum=s1+s2
        ans*=(self.fact[ssum]*self.ifact[s1])%self.mod*self.ifact[s2]%self.mod
        ans%=self.mod
        return ans,ssum 

    def addnode(self,x):
        return x[0],x[1]+1

    def _dfs(self,e,pa):
        edge=self.edge
        self.par[e]=pa
        self.ikigake.append(e)
        ans=self.unit
        for ne in edge[e]:
            if self.par[ne]!=-1:
                continue
            ans=self.func(ans,self.addnode(self._dfs(ne,e)))
            
        if pa!=e:
            self.dics[pa][e]=ans
        
        return ans
    
    def forward(self,start):
        self._dfs(start,start)
        
        
        for e in self.ikigake:
            pa=self.par[e]
            de=self.dics[e]
            nes=tuple(de.keys())
            nvals=tuple(de.values())
            l=len(nes)
            aleft=[self.unit]
            aright=[self.unit]
            cleft=self.unit
            cright=self.unit
            for i in range(l-1):
                aleft.append(self.func(aleft[-1],self.addnode(nvals[i])))
                aright.append(self.func(aright[-1],self.addnode(nvals[-i-1])))
                
            self.tot[e]=self.func(aright[-1],self.addnode(nvals[0]))
            for i,ne in enumerate(nes):
                if ne==pa:
                    continue
                self.dics[ne][e]=self.func(aleft[i],aright[-1-i])
                
        

def main():
    mod = 1000000007
    

    N = int(input())
    
    
    
    

    def tree_init(N):
        edgelist = [[] for _ in range(N)]
        elist=set()
        for a, b in [map(int, input().split()) for i in range(N-1)]:
            edgelist[a-1].append(b-1)
            edgelist[b-1].append(a-1)
            elist.add((a-1,b-1))
        return edgelist,elist

    edge,elist=tree_init(N)
    cb=comb(N)
    rt=rerooting(N,edge)
    rt.forward(0)

    for a in range(N):
        print(rt.tot[a][0])

if __name__ == "__main__":
    main()

Solution (Python):

import sys
sys.setrecursionlimit(10**7) 
import math



from functools import lru_cache



def input(): return sys.stdin.readline()[:-1]
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]

        
class comb:
    def __init__(self,N,mod=10**9+7):
        self.mod=mod
        self.fact=[0]*(N+1)
        self.ifact=[0]*(N+1)
        fact,ifact=self.fact,self.ifact
        fact[0],fact[1],ifact[0],ifact[1]=1,1,1,1
        for i in range(2,N+1):
            x=(fact[i-1]*i)%mod
            fact[i]=x
            ifact[i]=self.extgcd1(x,mod)
        

    @lru_cache(maxsize = None)
    def extgcd1(self,a0,b0):
        u,v,a,b=1,0,a0,b0
        while b:
            t,a=divmod(a,b)
            a,b,u,v=b,a,v,u-t*v
        if a!=1: 
            print("not 素")
            return -1
        return u%b0

    @lru_cache(maxsize = None)
    def comb(self,n,r): return (self.fact[n]*self.ifact[r]%self.mod)*self.ifact[n-r]%self.mod

    @lru_cache(maxsize = None)
    def mulcomb(self,n,*rs):
        ans=self.fact[n]
        for r in rs: ans=(ans*self.ifact[r])%self.mod
        return ans

class rerooting:
    def __init__(self,N,edge):
        
        self.unit=(1,0)
        self.mod=10**9+7
        self.edge=edge
        cb=comb(N)
        self.fact=cb.fact
        self.ifact=cb.ifact
        self.par=[-1]*N
        self.N=N
        self.visited=[0]*N
        self.dics=[dict() for _ in range(N)]
        self.ikigake=[]
        self.tot=[self.unit]*N
    
    
    def func(self,x,y):
        ifact=self.ifact
        mod=self.mod
        p1,s1=x
        p2,s2=y
        ans=(p1*p2)%mod
        ssum=s1+s2
        
        ans*=(self.fact[ssum]*ifact[s1])%mod*ifact[s2]%mod
        ans%=mod
        return ans,ssum 

    def addnode(self,x):
        return x[0],x[1]+1

    def _dfs(self,e,pa):
        edge=self.edge
        self.par[e]=pa
        self.ikigake.append(e)
        ans=self.unit
        for ne in edge[e]:
            if self.par[ne]!=-1:
                continue
            ans=self.func(ans,self.addnode(self._dfs(ne,e)))
            
        if pa!=e:
            self.dics[pa][e]=ans
        
        return ans
    
    def forward(self,start):
        self._dfs(start,start)
        
        
        for e in self.ikigake:
            pa=self.par[e]
            de=self.dics[e]
            nes=tuple(de.keys())
            nvals=tuple(de.values())
            l=len(nes)
            aleft=[self.unit]
            aright=[self.unit]
            cleft=self.unit
            cright=self.unit
            for i in range(l-1):
                aleft.append(self.func(aleft[-1],self.addnode(nvals[i])))
                aright.append(self.func(aright[-1],self.addnode(nvals[-i-1])))
                
            self.tot[e]=self.func(aright[-1],self.addnode(nvals[0]))
            for i,ne in enumerate(nes):
                if ne==pa:
                    continue
                self.dics[ne][e]=self.func(aleft[i],aright[-1-i])
                
        

def main():
    mod = 1000000007
    

    N = int(input())
    
    
    
    

    def tree_init(N):
        edgelist = [[] for _ in range(N)]
        elist=set()
        for a, b in [map(int, input().split()) for i in range(N-1)]:
            edgelist[a-1].append(b-1)
            edgelist[b-1].append(a-1)
            elist.add((a-1,b-1))
        return edgelist,elist

    edge,elist=tree_init(N)
    cb=comb(N)
    rt=rerooting(N,edge)
    rt.forward(0)

    for a in range(N):
        print(rt.tot[a][0])

if __name__ == "__main__":
    main()

Solution (Python):


from collections import deque
import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

n = int(readline())


mod = 10 ** 9 + 7
N = n + 5
bikkuri = [0 for i in range(N)]
bikkuri[0] = 1
gyaku = [0 for i in range(N)]
gyaku[0] = 1
for i in range(1, N):
    bikkuri[i] = (i * bikkuri[i - 1]) % mod
    gyaku[i] = pow(bikkuri[i], mod - 2, mod)

graph = [[] for _ in range(n + 1)]
m = map(int, read().split())
AB = zip(m, m)
for a, b in AB:
    graph[a].append(b)
    graph[b].append(a)


par = [-1] * (n + 1)
que = deque([])
que.append(1)
topo = []
while que:
    v = que.popleft()
    topo.append(v)
    for u in graph[v]:
        if u == par[v]:
            continue
        par[u] = v
        graph[u].remove(v)
        que.append(u)



dp1 = [0] * (n + 1)
size = [0] * (n + 1)
edge_index = [{} for _ in range(n + 1)]
dpl = [[] for _ in range(n + 1)]
dpr = [[] for _ in range(n + 1)]
for v in topo[::-1]:
    dp1[v] = 1
    size[v] = 1
    
    for u in graph[v]:
        size[v] += size[u]
        dp1[v] *= dp1[u]
        dp1[v] *= gyaku[size[u]]
    
    
    temp = 1
    for i in range(len(graph[v])):
        u = graph[v][i]
        edge_index[v][u] = i
        temp *= dp1[u]
        temp %= mod
        temp *= gyaku[size[u]]
        temp %= mod
        dpl[v].append(temp)
    
    temp = 1
    for i in range(len(graph[v]))[::-1]:
        u = graph[v][i]
        temp *= dp1[u]
        temp *= gyaku[size[u]]
        temp %= mod
        dpr[v].append(temp)
    dp1[v] *= bikkuri[size[v] - 1]
    dp1[v] %= mod


ans = [0] * (n + 1)
dp2 = [0] * (n + 1)

for v in topo:
    
    if par[v] == -1:
        dp2[v] = 1
        ans[v] = dp1[v]
    else:
        
        dp2[v] = 1
        p = par[v]
        
        
        v_idx = edge_index[p][v]
        dp2[v] *= dp2[p] * gyaku[n - size[p]]
        dp2[v] *= bikkuri[n - size[v] - 1]
        dp2[v] %= mod
        
        if dpl[p]:
            if v_idx - 1 >= 0:
                dp2[v] *= dpl[p][v_idx - 1]
                dp2[v] %= mod
            
            if v_idx < len(graph[p]) - 1:
                dp2[v] *= dpr[p][len(graph[p]) - 2 - v_idx]
                dp2[v] %= mod
    
    ans[v] = bikkuri[n - 1]
    if dpl[v]:
        ans[v] *= dpl[v][-1]
    ans[v] *= dp2[v] * gyaku[n - size[v]]
    ans[v] %= mod

for i in range(1, n + 1):
    print(ans[i])

Solution (Python):
import sys
readline = sys.stdin.readline


def treedoubling(P):
    
    P = P[:]
    N = len(P)
    D = [P[:]]
    dep = N.bit_length()
    for _ in range(dep):
        ret = [-1]*N
        for i in range(N):
            k = D[-1][i]
            if k != -1:
                ret[i] = D[-1][k]
        D.append(ret)
    return D

def lca(u, v, D, par, dist):
    if dist[u] > dist[v]:
        u, v = v, u
    
    ddif = dist[v] - dist[u]
    for i in range(ddif.bit_length()):
        if (1<<i)&ddif:
            v = D[i][v]
    
    if u != v:
        for cnt in range(dist[u].bit_length()-1, -1, -1):
            if D[cnt][u] != D[cnt][v]:
                u = D[cnt][u]
                v = D[cnt][v]
        u = par[u]
    return u

def parorder(Edge, p):
    N = len(Edge)
    par = [0]*N
    par[p] = -1
    stack = [p]
    order = []
    visited = set([p])
    ast = stack.append
    apo = order.append
    while stack:
        vn = stack.pop()
        apo(vn)
        for vf in Edge[vn]:
            if vf in visited:
                continue
            visited.add(vf)
            par[vf] = vn
            ast(vf)
    return par, order

def rerootingdp(P, L, intv = None):
    def merge(x, y):
        if x == intv:
            return y
        if y == intv:
            return x
        sa, da = x
        sb, db = y
        return (sa + sb, da*db%MOD)

    def g(m, vn):
        if m == intv:
            return (1, 1)
        sc, dc = m
        return (sc+1, dc*frac[sc]*fraci[sc+1]%MOD)
    
    N = len(L)
    dp = [None]*N
    LR = [intv]*N
    D = [intv]*N
    cld = [[] for _ in range(N)]
    for l in L[::-1]:        
        resl = intv
        for ci in cld[l]:
            LR[ci] = merge(LR[ci], resl)
            resl = merge(resl, dp[ci])
        resr = intv
        for ci in cld[l][::-1]:
            LR[ci] = merge(LR[ci], resr)
            resr = merge(resr, dp[ci])
        D[l] = resr
        dp[l] = g(resr, l)
        
        if P[l] != -1:
            cld[P[l]].append(l)
        
    U = [None]*N
    ans = [None]*N
    U[L[0]] = intv
    ans[L[0]] = dp[L[0]]
    for l in L[1:]:
        p = P[l]
        U[l] = g(merge(U[p], LR[l]), p)
        ans[l] = g(merge(D[l], U[l]), l)    
    return ans 

def getcld(p):
    res = [[] for _ in range(len(p))]
    for i, v in enumerate(p):
        if v == -1:
            continue
        res[v].append(i)
    return res


MOD = 10**9+7
def frac(limit):
    frac = [1]*limit
    for i in range(2,limit):
        frac[i] = i * frac[i-1]%MOD
    fraci = [None]*limit
    fraci[-1] = pow(frac[-1], MOD -2, MOD)
    for i in range(-2, -limit-1, -1):
        fraci[i] = fraci[i+1] * (limit + i + 1) % MOD
    return frac, fraci
frac, fraci = frac(1341398)

N = int(readline())
Edge = [[] for _ in range(N)]
for _ in range(N-1):
    a, b = map(int, readline().split())
    a -= 1
    b -= 1
    Edge[a].append(b)
    Edge[b].append(a)



P, L = parorder(Edge, 0)

Ans = [frac[a]*d%MOD for a, d in rerootingdp(P, L)]
print('\n'.join(map(str, Ans)))

Solution (Python):
import sys
input = sys.stdin.buffer.readline
from collections import deque

def main():
	N = int(input())
	edge = [[] for _ in range(N+1)]
	
	MOD = 10**9+7
	fac = [0]*(N+1)
	fac[0],fac[1] = 1,1
	invfac = [0]*(N+1)
	invfac[0],invfac[1] = 1,1

	for i in range(2,N+1):
		fac[i] = (fac[i-1]*i)%MOD

	invfac[-1] = pow(fac[-1],MOD-2,MOD)
	for i in range(N,0,-1):
		invfac[i-1] = (invfac[i]*i)%MOD
	
	for _ in range(N-1):
		a,b = map(int,input().split())
		edge[a].append(b)
		edge[b].append(a)

	proc = []
	parent = [0]*(N+1)
	q = deque([1])
	while q:
		now = q.pop()
		proc.append(now)
		for fol in edge[now]:
			if fol == parent[now]:
				continue
			parent[fol] = now
			q.append(fol)
	
	d_size = [0]*(N+1)
	d_dp = [1]*(N+1)

	for v in proc[::-1]:
		d_dp[v] *= fac[d_size[v]]
		d_dp[v] %= MOD
		p = parent[v]
		s = d_size[v]+1
		d_size[p] += s
		d_dp[p] *= d_dp[v]*invfac[s]
		d_dp[p] %= MOD
	
	u_size = [N-num-1 for num in d_size]
	u_dp = [1]*(N+1)
	
	for v in proc[1:]:
	    p = parent[v]
	    x = d_dp[p]
	    x *= u_dp[p]
	    x *= invfac[d_size[p]]
	    x *= fac[d_size[v]+1]
	    x *= pow(d_dp[v],MOD-2,MOD)
	    x %= MOD
	    x *= fac[u_size[v]-1]
	    x *= invfac[u_size[p]]
	    u_dp[v] = x%MOD
	
	u_size[1] = 0
	u_dp[1] = 1
	
	for i in range(1,N+1):
	    ret = d_dp[i]*u_dp[i]*fac[d_size[i]+u_size[i]]*invfac[d_size[i]]*invfac[u_size[i]]%MOD
	    print(ret)

if __name__ == "__main__":
	main()

Solution (Python):

import sys
from collections import defaultdict
MOD = 1000000007  


class Combination(object):

    def __init__(self, N, mod=MOD):
        fac, finv, inv = [0]*(N+1), [0]*(N+1), [0]*(N+1)
        fac[:2] = 1, 1
        finv[:2] = 1, 1
        inv[1] = 1
        for i in range(2, N+1):
            fac[i] = fac[i-1]*i % mod
            inv[i] = -inv[mod % i]*(mod//i) % mod
            finv[i] = finv[i-1]*inv[i] % mod
        self.N = N
        self.MOD = mod
        self.fac = fac
        self.finv = finv
        self.inv = inv

    def __call__(self, n, k):
        if n < k:
            return 0
        if n < 0 or k < 0:
            return 0
        b = (self.finv[k]*self.finv[n-k] % self.MOD)
        return (self.fac[n] * b) % self.MOD


def make_downward(E, N, s=0):
    
    front, back = 0, 1
    downward = [s]*N
    parent = [-1]*N
    for _ in range(N-1):
        v = downward[front]
        front += 1
        for u in E[v]:
            if u == parent[v]:
                continue
            parent[u] = v
            downward[back] = u
            back += 1
    
    return downward, parent


def solve(N: int, a: "List[int]", b: "List[int]"):
    
    E = [[] for _ in range(N)]
    for aa, bb in zip(a, b):
        E[aa-1].append(bb-1)
        E[bb-1].append(aa-1)

    
    cmb = Combination(N)

    
    downward, parent = make_downward(E, N)

    
    dp = [1]*N
    
    size = [0]*N

    
    
    for v in reversed(downward):
        for u in E[v]:
            if u == parent[v]:
                continue
            size[v] += size[u]+1
            dp[v] *= cmb.finv[size[u]+1]
            dp[v] %= MOD
            dp[v] *= dp[u]
            dp[v] %= MOD
        dp[v] *= cmb.fac[size[v]]
        dp[v] %= MOD

    
    
    for v in downward:
        for u in E[v]:
            if u == parent[v]:
                continue
            dp[u] = dp[v]
            dp[u] *= (size[u]+1)*cmb.inv[N-(size[u]+1)]
            dp[u] %= MOD

    for v in dp:
        print(v)
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    a = [int()] * (N - 1)  
    b = [int()] * (N - 1)  
    for i in range(N - 1):
        a[i] = int(next(tokens))
        b[i] = int(next(tokens))
    solve(N, a, b)


if __name__ == '__main__':
    main()

Solution (Python):

import sys
from collections import defaultdict
MOD = 1000000007  


class Combination(object):

    def __init__(self, N, mod=MOD):
        fac, finv, inv = [0]*(N+1), [0]*(N+1), [0]*(N+1)
        fac[:2] = 1, 1
        finv[:2] = 1, 1
        inv[1] = 1
        for i in range(2, N+1):
            fac[i] = fac[i-1]*i % mod
            inv[i] = -inv[mod % i]*(mod//i) % mod
            finv[i] = finv[i-1]*inv[i] % mod
        self.N = N
        self.MOD = mod
        self.fac = fac
        self.finv = finv
        self.inv = inv

    def __call__(self, n, k):
        if n < k:
            return 0
        if n < 0 or k < 0:
            return 0
        b = (self.finv[k]*self.finv[n-k] % self.MOD)
        return (self.fac[n] * b) % self.MOD


def solve(N: int, a: "List[int]", b: "List[int]"):
    
    E = [[] for _ in range(N)]
    for aa, bb in zip(a, b):
        E[aa-1].append(bb-1)
        E[bb-1].append(aa-1)

    
    cmb = Combination(N)

    
    front, back = -1, 1
    downward = [0]*N
    parent = [-1]*N
    for _ in range(N-1):
        front += 1
        v = downward[front]
        for u in E[v]:
            if u == parent[v]:
                continue
            parent[u] = v
            downward[back] = u
            back += 1
    

    
    dp = [1]*N
    
    size = [0]*N

    
    
    for v in reversed(downward):
        for u in E[v]:
            if u == parent[v]:
                continue
            size[v] += size[u]+1
            dp[v] *= cmb.finv[size[u]+1]
            dp[v] %= MOD
            dp[v] *= dp[u]
            dp[v] %= MOD
        dp[v] *= cmb.fac[size[v]]
        dp[v] %= MOD

    
    
    for v in downward:
        for u in E[v]:
            if u == parent[v]:
                continue
            dp[u] = dp[v]
            dp[u] *= (size[u]+1)*cmb.inv[N-(size[u]+1)]
            dp[u] %= MOD

    for v in dp:
        print(v)
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    a = [int()] * (N - 1)  
    b = [int()] * (N - 1)  
    for i in range(N - 1):
        a[i] = int(next(tokens))
        b[i] = int(next(tokens))
    solve(N, a, b)


if __name__ == '__main__':
    main()