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
from collections import defaultdict
from functools import lru_cache
MOD = 1000000007  


@lru_cache(maxsize=None)
def div(a, b):
    return (a * pow(b, MOD-2, MOD)) % MOD


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)

    
    curr = -1
    downward = [0]
    parent = [-1]*N
    while len(downward) < N:
        curr += 1
        v = downward[curr]
        for u in E[v]:
            if u == parent[v]:
                continue
            parent[u] = v
            downward.append(u)
    

    
    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
from functools import lru_cache
from collections import deque
MOD = 1000000007  


class Graph(object):
    def __init__(self, N):
        self.N = N
        self.E = defaultdict(list)

    def add_edge(self, src, dest, w=1):
        self.E[src].append((dest, w))
        self.E[dest].append((src, w))


@lru_cache(maxsize=None)
def div(a, b):
    return (a * pow(b, MOD-2, MOD)) % MOD


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]"):
    
    g = Graph(N)
    for aa, bb in zip(a, b):
        g.add_edge(aa-1, bb-1)

    
    cmb = Combination(N)

    
    curr = -1
    downward = [0]
    parent = [-1]*N
    while len(downward) < N:
        curr += 1
        v = downward[curr]
        for u, _ in g.E[v]:
            if u == parent[v]:
                continue
            parent[u] = v
            downward.append(u)
    

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

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

    
    
    for v in downward:
        for u, _ in g.E[v]:
            if u == parent[v]:
                continue
            d = div(dp[v], cmb(N-1, size[u]+1))
            d = div(d, dp[u])
            dp[u] *= cmb(N-1, size[u])
            dp[u] %= MOD
            dp[u] *= d
            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
from functools import lru_cache
from collections import deque


sys.setrecursionlimit(10**8)
INF = float("inf")

MOD = 1000000007  


class Graph(object):
    def __init__(self, N):
        self.N = N
        self.E = defaultdict(list)

    def add_edge(self, src, dest, w=1):
        self.E[src].append((dest, w))
        self.E[dest].append((src, w))


@lru_cache(maxsize=None)
def div(a, b):
    return (a * pow(b, MOD-2, MOD)) % MOD


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

    @lru_cache(maxsize=None)
    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]"):
    

    
    
    

    
    g = Graph(N)
    for aa, bb in zip(a, b):
        g.add_edge(aa-1, bb-1)

    
    cmb = Combination(N)

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

    
    queue = [(0, -1)]
    seen = [False]*N

    while queue:
        v, p = queue[-1]
        flag = True
        if seen[v] is False:
            for u, _ in g.E[v]:
                if u == p:
                    continue
                if seen[u] is False:
                    queue.append((u, v))
                    flag = False
        if flag is True:
            
            for u, _ in g.E[v]:
                if u == p:
                    continue
                size[v] += size[u]+1
                dp[v] *= cmb(size[v], size[u]+1)
                dp[v] %= MOD
                dp[v] *= dp[u]
                dp[v] %= MOD
            
            queue.pop()
            seen[v] = True
    
    

    
    
    

    
    queue = deque()
    queue.append((0, -1))

    while len(queue) > 0:
        v, p = queue.popleft()
        for u, _ in g.E[v]:
            if u == p:
                continue
            d = div(dp[v], cmb(N-1, size[u]+1))
            d = div(d, dp[u])
            dp[u] *= cmb(N-1, size[u])
            dp[u] %= MOD
            dp[u] *= d
            dp[u] %= MOD
            queue.append((u, v))

    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
sys.setrecursionlimit(10**9)

MOD = 10**9 + 7
n = int(input())
graph = [[] for _ in range(n)]
for _ in range(n - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)

MAX = n + 5
fact = [1] * (MAX + 1)  
finv = [1] * (MAX + 1)  
iinv = [1] * (MAX + 1)  
for i in range(2, MAX + 1):
    fact[i] = fact[i - 1] * i % MOD
    iinv[i] = MOD - iinv[MOD % i] * (MOD // i) % MOD
    finv[i] = finv[i - 1] * iinv[i] % MOD

ele_id = (1, 0)




dp = [[ele_id] * len(graph[i]) for i in range(n)]
ans = [ele_id] * n

add_func = lambda x: (x[0], x[1] + 1)


def merge_func(a, b):
    m = a[1] + b[1]
    dp_a = a[0] * finv[a[1]] % MOD
    dp_b = b[0] * finv[b[1]] % MOD
    c = (dp_a * dp_b % MOD) * fact[m] % MOD
    return (c, m)


def dfs1(v, v_p):
    dp_cum = ele_id
    for i, v_next in enumerate(graph[v]):
        if v_next == v_p:
            continue
        dp[v][i] = dfs1(v_next, v)
        dp_cum = merge_func(dp_cum, dp[v][i])
    return add_func(dp_cum)


def dfs2(v, v_p, dp_vp):
    for i, v_next in enumerate(graph[v]):
        if v_next == v_p:
            dp[v][i] = dp_vp

    dp_l = [ele_id] * (len(graph[v]) + 1)
    dp_r = [ele_id] * (len(graph[v]) + 1)
    for i in range(len(graph[v])):
        dp_l[i + 1] = merge_func(dp_l[i], dp[v][i])
    for i in reversed(range(len(graph[v]))):
        dp_r[i] = merge_func(dp_r[i + 1], dp[v][i])

    ans[v] = add_func(dp_l[-1])

    for i, v_next in enumerate(graph[v]):
        if v_next == v_p:
            continue
        dfs2(v_next, v, add_func(merge_func(dp_l[i], dp_r[i + 1])))


dfs1(0, -1)
dfs2(0, -1, ele_id)
for ans_i, _ in ans:
    print(ans_i)

Solution (Python):


import sys
sys.setrecursionlimit(10 ** 6)

MOD = 10 ** 9 + 7


class ModInt:
    def __init__(self, x):
        self.x = x % MOD

    def __str__(self):
        return str(self.x)

    __repr__ = __str__

    def __add__(self, other):
        return (
            ModInt(self.x + other.x) if isinstance(other, ModInt) else
            ModInt(self.x + other)
        )

    def __sub__(self, other):
        return (
            ModInt(self.x - other.x) if isinstance(other, ModInt) else
            ModInt(self.x - other)
        )

    def __mul__(self, other):
        return (
            ModInt(self.x * other.x) if isinstance(other, ModInt) else
            ModInt(self.x * other)
        )

    def __truediv__(self, other):
        return (
            ModInt(
                self.x * pow(other.x, MOD - 2, MOD)
            ) if isinstance(other, ModInt) else
            ModInt(self.x * pow(other, MOD - 2, MOD))
        )

    def __pow__(self, other):
        return (
            ModInt(pow(self.x, other.x, MOD)) if isinstance(other, ModInt) else
            ModInt(pow(self.x, other, MOD))
        )

    __radd__ = __add__

    def __rsub__(self, other):
        return (
            ModInt(other.x - self.x) if isinstance(other, ModInt) else
            ModInt(other - self.x)
        )

    __rmul__ = __mul__

    def __rtruediv__(self, other):
        return (
            ModInt(
                other.x * pow(self.x, MOD - 2, MOD)
            ) if isinstance(other, ModInt) else
            ModInt(other * pow(self.x, MOD - 2, MOD))
        )

    def __rpow__(self, other):
        return (
            ModInt(pow(other.x, self.x, MOD)) if isinstance(other, ModInt) else
            ModInt(pow(other, self.x, MOD))
        )


LI = lambda: list(map(int, input().split()))


N = int(input())
AB = [LI() for _ in range(N - 1)]


links = [[] for i in range(N)]
dp = [ModInt(1) for _ in range(N)]
c = [1] * N

MAX = 2 * (10 ** 5) + 5
fac, finv, inv = [None] * MAX, [None] * MAX, [None] * MAX


def comb_init():
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    inv[1] = 1
    for i in range(2, MAX):
        fac[i] = fac[i - 1] * i % MOD
        inv[i] = -inv[MOD%i] * int(MOD / i) % MOD
        finv[i] = finv[i - 1] * inv[i] % MOD


def comb(n, k):
    if n < k or n < 0 or k < 0:
        return 0
    return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD


def create_links():
    for a, b in AB:
        links[a - 1].append(b - 1)
        links[b - 1].append(a - 1)
    return links


def dfs1(v, p=-1):
    for u in links[v]:
        if u == p:
            continue
        dfs1(u, v)
        c[v] += c[u]
        dp[v] *= dp[u]
        dp[v] *= finv[c[u]]
    dp[v] *= fac[c[v] - 1]


def dfs2(v, p=-1):
    for u in links[v]:
        if u == p:
            continue
        dp[u] = dp[v] * c[u] * inv[(N - c[u])]
        dfs2(u, v)


def main():
    comb_init()
    create_links()
    dfs1(0)
    dfs2(0)
    [print(ans) for ans in dp]


if __name__ == "__main__":
    main()

Solution (Python):
import sys

def cmb(n, r, mod):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod

mod = 10**9+7 
N = 2*10**5
g1 = [1, 1] 
g2 = [1, 1] 
inverse = [0, 1] 

for i in range( 2, N + 1 ):
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )


input=sys.stdin.readline
write=sys.stdout.write

N=int(input())
hen={i:[] for i in range(1,N+1)}
for i in range(0,N-1):
    a,b=map(int,input().split())
    hen[a].append(b)
    hen[b].append(a)

parent={i:-1 for i in range(1,N+1)}
parent[1]=0
q=[]
q.append(1)
sub=[]
while q!=[]:
    while q!=[]:
        x=q.pop()
        for p in hen[x]:
            if parent[p]==-1:
                parent[p]=x
                sub.append(p)
        
        
        if q==[]:
            q=sub
            sub=[]
            break

ans={i:1 for i in range(1,N+1)}
subtreesize={i:1 for i in range(1,N+1)}
flag={i:0 for i in range(0,N+1)}
q=[]
for i in range(1,N+1):
    if i!=1 and len(hen[i])==1:
        q.append(i)


sub=[]
while q!=[]:
    while q!=[]:
        x=q.pop()
        p=parent[x]
        if p!=1:
            ans[p]=(ans[p]*ans[x]*g2[subtreesize[x]])%mod
            subtreesize[p]+=subtreesize[x]
            flag[p]+=1
            if flag[p]==len(hen[p])-1:
                ans[p]=(ans[p]*g1[subtreesize[p]-1])%mod
                sub.append(p)
        else:
            subtreesize[1]+=subtreesize[x]
            ans[1]=(ans[1]*ans[x]*g2[subtreesize[x]])%mod
            flag[1]+=1
            if flag[1]==len(hen[1]):
                ans[1]=(ans[1]*g1[subtreesize[1]-1])%mod
        
        
        if q==[]:
            q=sub
            sub=[]
            break

q=[1]
flag2={i:0 for i in range(1,N+1)}
flag2[1]=1
sub=[]
while q!=[]:
    while q!=[]:
        x=q.pop()
        for p in hen[x]:
            if flag2[p]==0:
                if len(hen[p])!=1:
                    ans[p]=(ans[x]*pow(N-subtreesize[p],mod-2,mod)*g1[subtreesize[p]]*g2[subtreesize[p]-1])%mod
                    flag2[p]=1
                    sub.append(p)
                else:
                    ans[p]=(ans[x]*pow(N-1,mod-2,mod))%mod

        
        
        if q==[]:
            q=sub
            sub=[]
            break

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

Solution (Python):
import sys

def cmb(n, r, mod):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod

mod = 10**9+7 
N = 2*10**5
g1 = [1, 1] 
g2 = [1, 1] 
inverse = [0, 1] 

for i in range( 2, N + 1 ):
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )


input=sys.stdin.readline
write=sys.stdout.write

N=int(input())
hen={i:[] for i in range(1,N+1)}
for i in range(0,N-1):
    a,b=map(int,input().split())
    hen[a].append(b)
    hen[b].append(a)

parent={i:-1 for i in range(1,N+1)}
parent[1]=0
q=[]
q.append(1)
sub=[]
while q!=[]:
    while q!=[]:
        x=q.pop()
        for p in hen[x]:
            if parent[p]==-1:
                parent[p]=x
                sub.append(p)
        
        
        if q==[]:
            q=sub
            sub=[]
            break

ans={i:1 for i in range(1,N+1)}
subtreesize={i:1 for i in range(1,N+1)}
flag={i:0 for i in range(0,N+1)}
q=[]
for i in range(1,N+1):
    if i!=1 and len(hen[i])==1:
        q.append(i)


sub=[]
while q!=[]:
    while q!=[]:
        x=q.pop()
        p=parent[x]
        if p!=1:
            ans[p]=(ans[p]*ans[x]*g2[subtreesize[x]])%mod
            subtreesize[p]+=subtreesize[x]
            flag[p]+=1
            if flag[p]==len(hen[p])-1:
                ans[p]=(ans[p]*g1[subtreesize[p]-1])%mod
                sub.append(p)
        else:
            subtreesize[1]+=subtreesize[x]
            ans[1]=(ans[1]*ans[x]*g2[subtreesize[x]])%mod
            flag[1]+=1
            if flag[1]==len(hen[1]):
                ans[1]=(ans[1]*g1[subtreesize[1]-1])%mod
        
        
        if q==[]:
            q=sub
            sub=[]
            break

q=[1]
flag2={i:0 for i in range(1,N+1)}
flag2[1]=1
sub=[]
while q!=[]:
    while q!=[]:
        x=q.pop()
        for p in hen[x]:
            if flag2[p]==0:
                if len(hen[p])!=1:
                    ans[p]=(ans[x]*pow(N-subtreesize[p],mod-2,mod)*g1[subtreesize[p]]*g2[subtreesize[p]-1])%mod
                    flag2[p]=1
                    sub.append(p)
                else:
                    ans[p]=(ans[x]*pow(N-1,mod-2,mod))%mod

        
        
        if q==[]:
            q=sub
            sub=[]
            break

for i in range(1,N+1):
    write(str(ans[i])+"\n")

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

mod = 10 ** 9 + 7
N = int(input())
X = [[] for i in range(N)]
for i in range(N-1):
    x, y = map(int, input().split())
    X[x-1].append(y-1)
    X[y-1].append(x-1)

P = [-1] * N
Q = deque([0])
R = []
while Q:
    i = deque.popleft(Q)
    R.append(i)
    for a in X[i]:
        if a != P[i]:
            P[a] = i
            X[a].remove(i)
            deque.append(Q, a)


unit = 1
merge = lambda a, b: a * b % mod
adj_bu = lambda a, i: a * inv(SIZE[i]) % mod
adj_td = lambda a, i, p: a * inv(N-SIZE[i]) % mod
adj_fin = lambda a, i: a * fa[N-1] % mod


nn = 200200
mod = 10**9+7

fa = [1] * (nn+1)
fainv = [1] * (nn+1)
for i in range(nn):
    fa[i+1] = fa[i] * (i+1) % mod
fainv[-1] = pow(fa[-1], mod-2, mod)
for i in range(nn)[::-1]:
    fainv[i] = fainv[i+1] * (i+1) % mod

inv = lambda i: fainv[i] * fa[i-1] % mod

SIZE = [1] * N
for i in R[1:][::-1]:
    SIZE[P[i]] += SIZE[i]

ME = [unit] * N
XX = [0] * N
TD = [unit] * N
for i in R[1:][::-1]:
    XX[i] = adj_bu(ME[i], i)
    p = P[i]
    ME[p] = merge(ME[p], XX[i])
XX[R[0]] = adj_fin(ME[R[0]], R[0])

for i in R:
    ac = TD[i]
    for j in X[i]:
        TD[j] = ac
        ac = merge(ac, XX[j])
    ac = unit
    for j in reversed(X[i]):
        TD[j] = adj_td(merge(TD[j], ac), j, i)
        ac = merge(ac, XX[j])
        XX[j] = adj_fin(merge(ME[j], TD[j]), j)

print(*XX, sep = "\n")

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

mod = 10 ** 9 + 7
N = int(input())
X = [[] for i in range(N)]
for i in range(N-1):
    x, y = map(int, input().split())
    X[x-1].append(y-1)
    X[y-1].append(x-1)

P = [-1] * N
Q = deque([0])
R = []
while Q:
    i = deque.popleft(Q)
    R.append(i)
    for a in X[i]:
        if a != P[i]:
            P[a] = i
            X[a].remove(i)
            deque.append(Q, a)


unit = 1
merge = lambda a, b: a * b % mod
adj_bu = lambda a, i: a * inv(SIZE[i]) % mod
adj_td = lambda a, i, p: a * inv(N-SIZE[i]) % mod
adj_fin = lambda a, i: a * fa[N-1] % mod


nn = 200200
mod = 10**9+7

fa = [1] * (nn+1)
fainv = [1] * (nn+1)
for i in range(nn):
    fa[i+1] = fa[i] * (i+1) % mod
fainv[-1] = pow(fa[-1], mod-2, mod)
for i in range(nn)[::-1]:
    fainv[i] = fainv[i+1] * (i+1) % mod

inv = lambda i: fainv[i] * fa[i-1] % mod

SIZE = [1] * N
for i in R[1:][::-1]:
    SIZE[P[i]] += SIZE[i]

ME = [unit] * N
XX = [0] * N
TD = [unit] * N
for i in R[1:][::-1]:
    XX[i] = adj_bu(ME[i], i)
    p = P[i]
    ME[p] = merge(ME[p], XX[i])
XX[R[0]] = adj_fin(ME[R[0]], R[0])

for i in R:
    ac = TD[i]
    for j in X[i]:
        TD[j] = ac
        ac = merge(ac, XX[j])
    ac = unit
    for j in X[i][::-1]:
        TD[j] = adj_td(merge(TD[j], ac), j, i)
        ac = merge(ac, XX[j])
        XX[j] = adj_fin(merge(ME[j], TD[j]), j)

print(*XX, sep = "\n")

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

mod = 10 ** 9 + 7
N = int(input())
X = [[] for i in range(N)]
for i in range(N-1):
    x, y = map(int, input().split())
    X[x-1].append(y-1)
    X[y-1].append(x-1)

P = [-1] * N
Q = deque([0])
R = []
while Q:
    i = deque.popleft(Q)
    R.append(i)
    for a in X[i]:
        if a != P[i]:
            P[a] = i
            X[a].remove(i)
            deque.append(Q, a)


unit = 1
merge = lambda a, b: a * b % mod
adj_bu = lambda a, i: a * inv(SIZE[i]) % mod
adj_td = lambda a, i, p: a * inv(N-SIZE[i]) % mod
adj_fin = lambda a, i: a * fa[N-1] % mod


nn = 200200
mod = 10**9+7

fa = [1] * (nn+1)
fainv = [1] * (nn+1)
for i in range(nn):
    fa[i+1] = fa[i] * (i+1) % mod
fainv[-1] = pow(fa[-1], mod-2, mod)
for i in range(nn)[::-1]:
    fainv[i] = fainv[i+1] * (i+1) % mod

inv = lambda i: fainv[i] * fa[i-1] % mod

SIZE = [1] * N
for i in reversed(R[1:]):
    SIZE[P[i]] += SIZE[i]

ME = [unit] * N
XX = [0] * N
TD = [unit] * N
for i in reversed(R[1:]):
    XX[i] = adj_bu(ME[i], i)
    p = P[i]
    ME[p] = merge(ME[p], XX[i])
XX[R[0]] = adj_fin(ME[R[0]], R[0])

for i in R:
    ac = TD[i]
    for j in X[i]:
        TD[j] = ac
        ac = merge(ac, XX[j])
    ac = unit
    for j in reversed(X[i]):
        TD[j] = adj_td(merge(TD[j], ac), j, i)
        ac = merge(ac, XX[j])
        XX[j] = adj_fin(merge(ME[j], TD[j]), j)

print(*XX, sep = "\n")

Solution (Python):
class Combination():
    def __init__(self, n, mod):
        self.mod = mod
        self.fac = [1]*(n+1)
        for i in range(1,n+1):
            self.fac[i] = self.fac[i-1] * i % self.mod
        self.invfac = [1]*(n+1)
        self.invfac[n] = pow(self.fac[n], self.mod - 2, self.mod)
        for i in range(n-1, 0, -1):
            self.invfac[i] = self.invfac[i+1] * (i+1) % self.mod
    
    def combination(self, n, r):
        return self.fac[n] * self.invfac[r] % self.mod * self.invfac[n-r] % self.mod
    
    def factorial(self, i):
        return self.fac[i]
    
    def invfactorial(self, i):
        return self.invfac[i]


class Rerooting(Combination):
    def __init__(self, adjacent, n, mod):
        super(Rerooting, self).__init__(n, mod)
        self.n = n
        self.adj = adjacent   
        
        self.order = []
        stack = [0]
        self.parent = [-1]*(n)
        while stack:
            node = stack.pop()
            self.order.append(node)
            for child in self.adj[node]:
                if self.parent[node] == child:
                    continue
                stack.append(child)
                self.parent[child] = node
    
    def merge(self, parent, child):
        
        self.size[parent] += self.size[child]
        self.dp[parent] *= self.combination(self.size[parent]-1,self.size[child])
        self.dp[parent] %= self.mod
        self.dp[parent] *= self.dp[child]
        self.dp[parent] %= self.mod
        return self.dp[parent]

    def remerge(self, parent, child):
        
        self.dp[child] = self.size[child]*self.dp[parent]
        self.dp[child] *= pow(self.n-self.size[child], self.mod -2, self.mod)
        self.dp[child] %= self.mod
        return self.dp[child]

    def calc_subtree(self):
        
        
        self.dp = [1]*(self.n)
        self.size = [1]*(self.n)
        for node in self.order[::-1]:
            if self.parent[node] == -1:
                continue
            self.merge(self.parent[node], node)

    def root_subtree(self):
        
        for node in self.order[1:]:
            p = self.parent[node]
            self.remerge(p, node)
        return self.dp
        

def main():
    import sys
    input = lambda: sys.stdin.buffer.readline().rstrip()
    n = int(input())
    mod = 10**9 + 7
    adj = [[] for i in range(n)]
    for i in range(n-1):
        a, b = map(lambda x: int(x)-1, input().split())
        adj[a].append(b)
        adj[b].append(a)

    r = Rerooting(adj, n, mod)
    r.calc_subtree()
    dp = r.root_subtree()

    for ans in dp:
        print(ans)


if __name__ == '__main__':
    main()

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

MOD = 10 ** 9 + 7

class Factorial:
    def __init__(self, n, mod):
        self.f = [1]
        self.mod = mod
        for j in range(1, n + 1):
            self.f.append(self.f[-1] * j % mod)
        self.i = [pow(self.f[-1], mod - 2, mod)]
        for j in range(n, 0, -1):
            self.i.append(self.i[-1] * j % mod)
        self.i.reverse()
    def factorial(self, j):
        return self.f[j]
    def ifactorial(self, j):
        return self.i[j]
    def comb(self, n, k):
        return self.f[n] * self.i[n - k] % self.mod * self.i[k] % self.mod if n >= k else 0

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

F = Factorial(N + 2, MOD)

root = 1
stack = [root]
check = [False] * (N + 1)
check[root] = True
p = [0] * (N + 1) 

DAG = []

while stack:
    now_ = stack.pop()
    DAG.append(now_)
    for next_ in G[now_]:
        if check[next_]:
            continue
        stack.append(next_)
        check[next_] = True
        p[next_] = now_

size1 = [0] * (N + 1)
dp1 = [1] * (N + 1)

for now_ in DAG[::-1]:
    size1[now_] += 1
    size1[p[now_]] += size1[now_]
    dp1[now_] *= F.factorial(size1[now_] - 1)
    dp1[now_] %= MOD
    dp1[p[now_]] *= dp1[now_] * F.ifactorial(size1[now_])
    dp1[p[now_]] %= MOD




size2 = [N - size1[i] + 1 for i in range(N + 1)]
dp2 = [1] * (N + 1)

for i in DAG:
    parent = i
    for now_ in G[i]:
        if now_ == p[i]:
            continue
        x = dp1[parent]
        x *= F.ifactorial(size1[parent] - 1)
        x *= F.factorial(size1[now_])
        x *= pow(dp1[now_], MOD - 2, MOD)
        x *= dp2[parent]
        x *= F.ifactorial(size2[parent] - 1)
        x *= F.factorial(size2[now_] - 2)
        dp2[now_] = x % MOD
 



for i in range(1, N + 1):
    ans =  dp1[i] * F.ifactorial(size1[i] - 1) * dp2[i] * F.ifactorial(size2[i] - 1) * F.factorial(N - 1)
    print (ans % MOD)

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

MOD = 10 ** 9 + 7

class Factorial:
    def __init__(self, n, mod):
        self.f = [1]
        self.mod = mod
        for j in range(1, n + 1):
            self.f.append(self.f[-1] * j % mod)
        self.i = [pow(self.f[-1], mod - 2, mod)]
        for j in range(n, 0, -1):
            self.i.append(self.i[-1] * j % mod)
        self.i.reverse()
    def factorial(self, j):
        return self.f[j]
    def ifactorial(self, j):
        return self.i[j]
    def comb(self, n, k):
        return self.f[n] * self.i[n - k] % self.mod * self.i[k] % self.mod if n >= k else 0

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

F = Factorial(N + 2, MOD)

root = 1
stack = [root]
check = [False] * (N + 1)
check[root] = True
p = [0] * (N + 1) 

DAG = []

while stack:
    now_ = stack.pop()
    DAG.append(now_)
    for next_ in G[now_]:
        if check[next_]:
            continue
        stack.append(next_)
        check[next_] = True
        p[next_] = now_

size1 = [0] * (N + 1)
dp1 = [1] * (N + 1)

for now_ in DAG[::-1]:
    size1[now_] += 1
    size1[p[now_]] += size1[now_]
    dp1[now_] *= F.factorial(size1[now_] - 1)
    dp1[now_] %= MOD
    dp1[p[now_]] *= dp1[now_] * F.ifactorial(size1[now_])
    dp1[p[now_]] %= MOD




size2 = [N - size1[i] + 1 for i in range(N + 1)]
dp2 = [1] * (N + 1)

for now_ in DAG[1::]:
    parent = p[now_]
    x = dp1[parent]
    x *= F.ifactorial(size1[parent] - 1)
    x *= F.factorial(size1[now_])
    x *= pow(dp1[now_], MOD - 2, MOD)
    x *= dp2[parent]
    x *= F.ifactorial(size2[parent] - 1)
    x *= F.factorial(size2[now_] - 2)
    dp2[now_] = x % MOD
 



for i in range(1, N + 1):
    ans =  dp1[i] * F.ifactorial(size1[i] - 1) * dp2[i] * F.ifactorial(size2[i] - 1) * F.factorial(N - 1)
    print (ans % MOD)

Solution (Python):

import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))


N = ir()
graph = [[] for _ in range(N+1)]  
for _ in range(N-1):
    a, b = lr()
    graph[a].append(b)
    graph[b].append(a)

MOD = 10 ** 9 + 7

fact = [1] * (N + 10)
for n in range(1, N + 10):
    fact[n] = n * fact[n - 1] % MOD
fact_inv = [1] * (N + 10)
fact_inv[-1] = pow(fact[-1], MOD - 2, MOD)
for n in range(N + 9, 0, -1):
    fact_inv[n - 1] = fact_inv[n] * n % MOD

root = 1
parent = [0] * (N+1)
order = []
stack = [root]
while stack:
    cur = stack.pop()
    order.append(cur)
    for next in graph[cur]:
        if next == parent[cur]:
            continue
        parent[next] = cur
        stack.append(next)

size_down = [0] * (N+1)  
dp_down = [1] * (N+1)  
for v in order[::-1]:
    dp_down[v] *= fact[size_down[v]]
    dp_down[v] %= MOD
    p = parent[v]
    s = size_down[v] + 1
    size_down[p] += s
    dp_down[p] *= fact_inv[s] * dp_down[v]
    dp_down[p] %= MOD

size_up = [N-x-1 for x in size_down]  
dp_up = [1] * (N+1)  
for v in order[1:]:
    p = parent[v]
    x = dp_down[p]
    x *= dp_up[p]
    x *= fact_inv[size_down[p]]
    x *= fact[size_down[v] + 1]
    x *= pow(dp_down[v], MOD-2, MOD)
    x %= MOD
    x *= fact[size_up[v]-1]
    x *= fact_inv[size_up[p]]
    dp_up[v] = x % MOD

for xd, xu, sd, su in zip(dp_down[1:], dp_up[1:], size_down[1:], size_up[1:]):
    answer = xd * xu * fact[sd+su] * fact_inv[sd] * fact_inv[su] % MOD
    print(answer % MOD)