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 ** 5 + 5)




def prepare(n, MOD):
    f = 1
    factorials = [1]  
    for m in range(1, n + 1):
        f *= m
        f %= MOD
        factorials.append(f)
    inv = pow(f, MOD - 2, MOD)
    invs = [1] * (n + 1)
    invs[n] = inv
    for m in range(n, 1, -1):
        inv *= m
        inv %= MOD
        invs[m - 1] = inv

    return factorials, invs


def nhr(factorials, invs, n, r, MOD):
    return factorials[n + r - 1] * invs[n - 1] * invs[r] % MOD


def dfs0(links):
    q = [(0, -1)]
    while q:
        v, p = q.pop()
        links[v].discard(p)
        links[v] = list(links[v])
        q.extend((u, v) for u in links[v])


def dfs1(links, st_count_fwd, st_count_bwd, st_pattern_fwd, st_pattern_bwd):
    q = [(0, -1, 0)]
    while q:
        v, p, o = q.pop()
        if o == 0:
            
            q.append((v, p, 1))
            q.extend((u, v, 0) for u in links[v])
        else:
            
            curr_count = [0]
            curr_pattern = [1]
            for u in links[v]:
                stc_u = st_count_fwd[u][-1] + 1
                new_pattern = factorials[curr_count[-1] + stc_u] * invs[curr_count[-1]] * invs[stc_u] % MOD
                curr_pattern.append(new_pattern * curr_pattern[-1] * st_pattern_fwd[u][-1] % MOD)
                curr_count.append(curr_count[-1] + stc_u)
            st_count_fwd[v] = curr_count
            st_pattern_fwd[v] = curr_pattern
            curr_count = [0]
            curr_pattern = [1]
            for u in reversed(links[v]):
                stc_u = st_count_fwd[u][-1] + 1
                new_pattern = factorials[curr_count[-1] + stc_u] * invs[curr_count[-1]] * invs[stc_u] % MOD
                curr_pattern.append(new_pattern * curr_pattern[-1] * st_pattern_fwd[u][-1] % MOD)
                curr_count.append(curr_count[-1] + stc_u)
            st_count_bwd[v] = curr_count[::-1]
            st_pattern_bwd[v] = curr_pattern[::-1]


def dfs2(links, st_count_fwd, st_count_bwd, st_pattern_fwd, st_pattern_bwd, ans):
    def sub(v, pc, pp):
        
        if pc == 0:
            ans[v] = st_pattern_fwd[v][-1]
        else:
            cc = st_count_fwd[v][-1]
            cp = st_pattern_fwd[v][-1]
            pattern = factorials[cc + pc] * invs[cc] * invs[pc] % MOD
            pattern = pattern * cp * pp % MOD
            ans[v] = pattern

        for i, u in enumerate(links[v]):
            fc = st_count_fwd[v][i]
            fp = st_pattern_fwd[v][i]
            bc = st_count_bwd[v][i + 1]
            bp = st_pattern_bwd[v][i + 1]
            p1 = factorials[fc + bc] * invs[fc] * invs[bc] % MOD
            p1 = p1 * fp * bp % MOD
            p2 = factorials[fc + bc + pc] * invs[fc + bc] * invs[pc] % MOD
            p2 = p2 * p1 * pp % MOD
            
            sub(u, fc + bc + pc + 1, p2)

    sub(0, 0, 1)


n, *ab = map(int, sys.stdin.buffer.read().split())
links = [set() for _ in range(n)]
for a, b in zip(ab[0::2], ab[1::2]):
    a -= 1
    b -= 1
    links[a].add(b)
    links[b].add(a)
MOD = 10 ** 9 + 7
factorials, invs = prepare(n, MOD)
st_count_fwd = [[] for _ in range(n)]
st_count_bwd = [[] for _ in range(n)]
st_pattern_fwd = [[] for _ in range(n)]
st_pattern_bwd = [[] for _ in range(n)]
ans = [0] * n

dfs0(links)
dfs1(links, st_count_fwd, st_count_bwd, st_pattern_fwd, st_pattern_bwd)

dfs2(links, st_count_fwd, st_count_bwd, st_pattern_fwd, st_pattern_bwd, ans)
print('\n'.join(map(str, ans)))

Solution (Python):
import sys;input=sys.stdin.readline
import sys
mod = pow(10, 9) + 7
sys.setrecursionlimit(pow(10, 8))

def power(x, y):
    if   y == 0: return 1
    elif y == 1	 : return x % mod
    elif y % 2 == 0 : return power(x, y//2)**2 % mod
    else: return power(x, (y-1)//2)**2 * x % mod
    
def mul(a, b):
    return ((a % mod) * (b % mod)) % mod

def div(a, b):
    return mul(a, power(b, mod-2))
def div2(a, b):
    return mul(a, modinv(b))

def modinv(a):
    b, u, v = mod, 1, 0
    while b:
        t = a//b
        a, u = a-t*b, u-t*v
        a, b, u, v = b, a, v, u
    u %= mod
    return u

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
    import sys
    mod = pow(10, 9) + 7
    sys.setrecursionlimit(pow(10, 8))

NNN = (10**6)
g1 = [1, 1]
g2 = [1, 1]
inverse = [0, 1]

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

from collections import deque
N, = map(int, input().split())
d = [list() for _ in range(N+1)]
d2 = [list() for _ in range(N+1)]
for _ in range(N-1):
    a, b = map(int, input().split())
    d[a].append(b)
    d[b].append(a)

queue=deque([1])
vs = set([1])
vs_bfs = list()
parents = [0] * (N+1)
while queue:
    v = queue.popleft()
    vs_bfs.append(v)
    for u in d[v]:
        if u in vs:
            continue
        parents[u] = v
        vs.add(u)
        queue.append(u)
        d2[v].append(u)

dp1 = [0 for _ in range(N+1)]
sss = [0 for _ in range(N+1)]
for v in vs_bfs[::-1]:
    t = 1
    ts = []
    for u in d2[v]:
        t = mul(dp1[u], t)
        ts.append(sss[u])
    st = sum(ts)
    sss[v] = st + 1
    for tt in ts:
        t = mul(cmb(st, tt, mod), t)
        st -= tt
    dp1[v] = t


dp2 = [0]*(N+1)
for v in vs_bfs:
    if v == 1:
        dp2[v] = dp1[v]
        continue
    p = parents[v]

    t = div2(dp2[p], mul(dp1[v], cmb(N-1, sss[v], mod)))
    dp2[v] = mul(mul(dp1[v], t), cmb(N-1, N-sss[v], mod))



for x in dp2[1:]:
    print(x)

Solution (Python):
MOD = 10 ** 9 + 7
fac = [1] * (2 * 10 ** 5 + 10)
for i in range(len(fac) - 1):
    fac[i + 1] = fac[i] * (i + 1) % MOD


def euler_tour(G, root=0):
    n = len(G)
    euler = []
    dq = [root]
    visited = [0] * n
    while dq:
        u = dq.pop()
        euler += [u]
        if visited[u]:
            continue
        dq += [u]
        for v in G[u]:
            if visited[v]:
                continue
            
            else:
                dq += [v]
        visited[u] = 1
    return euler


n = int(input())
g = [[] for _ in range(n)]
for _ in range(n - 1):
    a, b = map(int, input().split())
    g[a - 1].append(b - 1)
    g[b - 1].append(a - 1)
e = euler_tour(g)
pr = [-1] * n
d = [0] * n
for i, x in enumerate(e):
    if pr[x] == -1:
        pr[x] = i
    else:
        d[x] = (i - pr[x]) // 2
s = [0]
p = [0] * n
v = [0] * n
for node in e:
    if v[node]:
        for t in g[node]:
            if d[t] <= d[node]:
                p[node] = p[node] * \
                    pow(fac[d[t] + 1], MOD - 2, MOD) * p[t] % MOD
    else:
        v[node] = 1
        p[node] = fac[d[node]]
s = [0]
ans = [0] * n
ans[0] = p[0]
while s:
    p = s.pop()
    for node in g[p]:
        if not ans[node]:
            ans[node] = ans[p] * (d[node] + 1) * \
                pow(n - d[node] - 1, MOD - 2, MOD) % MOD
            s.append(node)
for row in ans:
    print(row)

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

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

C = lambda a, b: fa[a] * fainv[b] % mod * fainv[a-b] % mod if 0 <= b <= a else 0

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)

BU = [1] * N
TD = [1] * N
SI = [1] * N
for i in R[::-1]:
    a = 1
    s = 0
    for j in X[i]:
        a = a * BU[j] * fainv[SI[j]] % mod
        s += SI[j]
    SI[i] = s + 1
    BU[i] = fa[s] * a % mod

for i in R:
    c = len(X[i])
    AL = [1] * (c + 1)
    AR = [1] * (c + 1)
    for j in range(c):
        AL[j+1] = AL[j] * BU[X[i][j]] % mod * fainv[SI[X[i][j]]] % mod
    for j in range(c)[::-1]:
        AR[j] = AR[j+1] * BU[X[i][j]] % mod * fainv[SI[X[i][j]]] % mod
    for j in range(c):
        TD[X[i][j]] = TD[i] * fainv[N - SI[i]] % mod * AL[j] % mod * AR[j+1] % mod * fa[N - 1 - SI[X[i][j]]] % mod

for i in range(N):
    print(BU[i] * TD[i] % mod * C(N-1, SI[i] - 1) % mod)

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


class Combination:
    """階乗とその逆元のテーブルをO(N)で事前作成し、組み合わせの計算をO(1)で行う"""
    def __init__(self, n, MOD):
        self.fact = [1]
        for i in range(1, n + 1):
            self.fact.append(self.fact[-1] * i % MOD)
        self.inv_fact = [0] * (n + 1)
        self.inv_fact[n] = pow(self.fact[n], MOD - 2, MOD)
        for i in reversed(range(n)):
            self.inv_fact[i] = self.inv_fact[i + 1] * (i + 1) % MOD
        self.MOD = MOD

    def factorial(self, k):
        """k!を求める O(1)"""
        return self.fact[k]

    def inverse_factorial(self, k):
        """k!の逆元を求める O(1)"""
        return self.inv_fact[k]

    def permutation(self, k, r):
        """kPrを求める O(1)"""
        if k < r:
            return 0
        return (self.fact[k] * self.inv_fact[k - r]) % self.MOD

    def combination(self, k, r):
        """kCrを求める O(1)"""
        if k < r:
            return 0
        return (self.fact[k] * self.inv_fact[k - r] * self.inv_fact[r]) % self.MOD


def solve(tree, root):
    def dfs1():
        st1 = deque([root])
        st2 = deque([root])
        
        while st1:
            v = st1.pop()
            for nxt_v in tree[v]:
                if nxt_v in par:
                    continue
                else:
                    par[nxt_v] = v
                    st1.append(nxt_v)
                    st2.append(nxt_v)
        
        while st2:
            v = st2.pop()
            res = 1
            c = 1
            for nxt_v in tree[v]:
                if nxt_v == par[v]:
                    continue
                else:
                    res *= dist1[nxt_v]
                    res *= comb.inv_fact[cnt[nxt_v]]
                    res %= MOD
                    c += cnt[nxt_v]
            cnt[v] = c
            dist1[v] = res * comb.fact[c - 1] % MOD
    def dfs2():
        q = deque([(root, 0, 0)])
        while q:
            v, par_val, par_cnt = q.pop()
            tmp_val = {}
            tmp_cnt = {}
            for nxt_v in tree[v]:
                if nxt_v == par[v]:
                    tmp_val[nxt_v] = par_val
                    tmp_cnt[nxt_v] = par_cnt
                else:
                    tmp_val[nxt_v] = dist1[nxt_v]
                    tmp_cnt[nxt_v] = cnt[nxt_v]
            res = 1
            c = 1
            for nxt_v in tmp_val:
                    res *= tmp_val[nxt_v]
                    res *= comb.inv_fact[tmp_cnt[nxt_v]]
                    res %= MOD
                    c += tmp_cnt[nxt_v]
            tmp_cnt[v] = c
            dist2[v] = res * comb.fact[c - 1] % MOD
            for nxt_v in tree[v]:
                if nxt_v == par[v]:
                    continue
                else:
                    tmp = dist2[v]\
                            * pow(tmp_val[nxt_v], MOD - 2, MOD) * comb.fact[tmp_cnt[nxt_v]] \
                            * comb.inv_fact[tmp_cnt[v] - 1] \
                            * comb.fact[tmp_cnt[v] - 1 - tmp_cnt[nxt_v]] % MOD
                    q.append((nxt_v, tmp, c - cnt[nxt_v]))

    par = {root: -1}
    dist1 = [0] * n
    cnt = [0] * n
    dist2 = [0] * n
    dfs1()
    dfs2()
    return dist2


n = int(input())
info = [list(map(int, input().split())) for i in range(n - 1)]
MOD = 10 ** 9 + 7

tree = [[] for i in range(n)]
for a, b in info:
    a -= 1
    b -= 1
    tree[a].append(b)
    tree[b].append(a)

comb = Combination(10 ** 6, MOD)
for i in solve(tree, 0):
    print(i % MOD)

Solution (Python):

from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    def dfs(x):
        fx = ans[x]
        nf = fx*inv[s[x]-1]%mod
        sx = s[x]
        for y in v[x]:
            sy = s[y]
            nsx = sx-sy
            nsy = s[x]
            if ans[y] == None:
                fy = nf*s[y]*f[nsy-1]*p[nsx]%mod
                ans[y] = fy
                s[x] = nsx
                s[y] = nsy
                dfs(y)
                s[x] = sx
                s[y] = sy

    n = I()
    f = [1]
    for i in range(1,n+1):
        f.append(f[-1]*i%mod)
    inv = [None]*(n+1)
    inv[n] = pow(f[n],mod-2,mod)
    for i in range(n)[::-1]:
        inv[i] = inv[i+1]*(i+1)%mod

    v = [[] for i in range(n)]
    for i in range(n-1):
        a,b = LI()
        a -= 1
        b -= 1
        v[a].append(b)
        v[b].append(a)
    d = [0]*n
    d[0] = 1
    q = deque([0])
    p = [None]*n
    while q:
        x = q.popleft()
        nd = d[x]+1
        for y in v[x]:
            if not d[y]:
                d[y] = nd
                p[y] = x
                q.append(y)
    V = list(range(n))
    V.sort(key = lambda x:-d[x])
    m = d[V[0]]
    s = [0]*n
    res = 1
    for i in V:
        j = p[i]
        s[i] += 1
        if j != None:
            s[j] += s[i]
            res *= inv[s[i]]
        if d[i] == m:
            continue
        res *= f[s[i]-1]
        res %= mod
    ans = [None]*n
    ans[0] = res
    p = [pow(i,mod-2,mod) for i in range(n+1)]
    dfs(0)
    for i in ans:
        print(i)
    return


if __name__ == "__main__":
    solve()

Solution (Python):
n = int(input())
big = 1
mod = 10 ** 9 + 7
for i in range(1,n):
  big *= i
  big %= mod
def inv(x):
  y = 1
  while x != 1:
    y *= mod // x + 1
    y %= mod
    x -= mod % x
  return y
tribe = [1 for _ in range(n)]
we = [1 for _ in range(n)]
peer = [[] for _ in range(n)]
for _ in range(n-1):
  a,b = map(int,input().split())
  a -= 1
  b -= 1
  peer[a].append(b)
  peer[b].append(a)
seen = [0 for _ in range(n)]
pre = [0 for _ in range(n)]
seen[0] = 1
rank = []
now = [0]
while now:
  rank.append(now)
  last = now
  now = []
  for x in last:
    for y in peer[x]:
      if seen[y] == 0:
        seen[y] = 1
        now.append(y)
        pre[y] = x



pre[0] = 10**6
rank.reverse()
for z in rank:
  if z == [0]:
    continue
  for w in z:
    tribe[pre[w]] += tribe[w]
    we[pre[w]] *= tribe[w] * we[w]
    we[pre[w]] %= mod


rank.reverse()
for z in rank:
  if z == [0]:
    continue
  for w in z:
    tmp = we[pre[w]]
    tmp *= inv(we[w]*tribe[w]%mod)
    tmp *= n - tribe[w]
    we[w] *= tmp
    we[w] %= mod

for i in range(n):
  print(big*inv(we[i])%mod)

Solution (Python):
import sys
input = sys.stdin.readline
from collections import deque
mod = 10**9+7
rng = 200100
fctr = [1]
finv = [1]
for i in range(1,rng):
  fctr.append(fctr[-1]*i%mod)
n = int(input())
ab = [list(map(int,input().split())) for i in range(n-1)]
graph = [[] for i in range(n+1)]
deg = [0]*(n+1)
for a,b in ab:
  graph[a].append(b)
  graph[b].append(a)
  deg[a] += 1
  deg[b] += 1
deg[1] += 1
stack = [1]
cnt = [0]*(n+1)
for i in range(2,n+1):
  if deg[i] == 1:
    stack.append(i)
    cnt[i] = 1
dp = [[] for i in range(n+1)]
while stack:
  x = stack.pop()
  if dp[x]:
    cnt[x] = sum(dp[x])+1
  for y in graph[x]:
    if deg[y] > 1:
      dp[y].append(cnt[x])
      deg[y] -= 1
      if deg[y] == 1:
        stack.append(y)
def euler_tour(G, root=1):
  n = len(G)
  euler = []
  dq = deque([root])
  dq2 = deque()
  visited = [0]*(n+1)
  while dq:
    u = dq.pop()
    euler += [u]
    if visited[u]:
      continue
    for v in G[u]:
      if visited[v]:
        dq += [v]
    
      else:
        dq2 += [v]
    dq.extend(dq2)
    dq2 = deque()
    visited[u] = 1
  return euler
order = euler_tour(graph)
ans1 = fctr[n]
for i in range(1,n+1):
  ans1 = (ans1*pow(cnt[i],mod-2,mod))%mod
ans = [0]*(n+1)
ans[1] = ans1
for i in range(1,len(order)):
  prv = order[i-1]
  now = order[i]
  no = cnt[now]
  cnt[prv] -= cnt[now]
  cnt[now] += cnt[prv]
  pr = cnt[prv]
  if ans[now]:
    continue
  ans[now] = ans[prv]*pow(pr,mod-2,mod)*no%mod
ans = ans[1:]
print(*ans,sep="\n")

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

nn = 202020
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

C = lambda a, b: fa[a] * fainv[b] * fainv[a-b] % mod if 0 <= b <= a else 0

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)

BU = [1] * N
TD = [1] * N
SI = [1] * N
for i in R[::-1]:
    a = 1
    s = 0
    for j in X[i]:
        a = a * BU[j] * fainv[SI[j]] % mod
        s += SI[j]
    SI[i] = s + 1
    BU[i] = fa[s] * a % mod

for i in R:
    a = TD[i] * fainv[N - SI[i]]
    for j in X[i]:
        a = a * BU[j] * fainv[SI[j]] % mod
    for j in X[i]:
        TD[j] = a * pow(BU[j], mod-2, mod) % mod * fa[SI[j]] % mod * fa[N - 1 - SI[j]] % mod

for i in range(N):
    print(BU[i] * TD[i] % mod * C(N-1, SI[i] - 1) % mod)

Solution (Python):

from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    def dfs(x):
        fx = ans[x]
        nf = fx*inv[s[x]-1]%mod
        sx = s[x]
        for y in v[x]:
            sy = s[y]
            nsx = sx-sy
            nsy = s[x]
            if ans[y] == None:
                fy = nf*s[y]*f[nsy-1]*pow(nsx,mod-2,mod)%mod
                ans[y] = fy
                s[x] = nsx
                s[y] = nsy
                dfs(y)
                s[x] = sx
                s[y] = sy

    n = I()
    f = [1]
    for i in range(1,n+1):
        f.append(f[-1]*i%mod)
    inv = [None]*(n+1)
    inv[n] = pow(f[n],mod-2,mod)
    for i in range(n)[::-1]:
        inv[i] = inv[i+1]*(i+1)%mod

    v = [[] for i in range(n)]
    for i in range(n-1):
        a,b = LI()
        a -= 1
        b -= 1
        v[a].append(b)
        v[b].append(a)
    d = [0]*n
    d[0] = 1
    q = deque([0])
    p = [None]*n
    while q:
        x = q.popleft()
        nd = d[x]+1
        for y in v[x]:
            if not d[y]:
                d[y] = nd
                p[y] = x
                q.append(y)
    V = list(range(n))
    V.sort(key = lambda x:-d[x])
    m = d[V[0]]
    s = [0]*n
    res = 1
    for i in V:
        j = p[i]
        s[i] += 1
        if j != None:
            s[j] += s[i]
            res *= inv[s[i]]
        if d[i] == m:
            continue
        res *= f[s[i]-1]
        res %= mod
    ans = [None]*n
    ans[0] = res
    dfs(0)
    for i in ans:
        print(i)
    return


if __name__ == "__main__":
    solve()

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

mod = 10**9+7

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

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

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

Child = [1]*N
Score = [1]*N

def dfs1(s):
    stack = [s]
    Ind = [0]*N
    while stack:
        p = stack[-1]
        
        
        
        if Ind[p] == len(graph[p]):
            stack.pop()
            par = -1
            if len(stack) > 0:
                par = stack[-1]
            P = []
            for ch in graph[p]:
                if ch == par: continue
                Child[p] += Child[ch]
                P.append([Score[ch], Child[ch]])
            tmp = Child[p]-1
            for s, c in P:
                Score[p] = (Score[p] * s * cmb(tmp, c)) % mod
                tmp -= c
        elif len(stack) > 1 and stack[-2] == graph[p][Ind[p]]:
            Ind[p] += 1
        else:
            stack.append(graph[p][Ind[p]])
            Ind[p] += 1

ans = [-1]*N

def dfs2(s):
    stack = [s]
    ans[s] = Score[s]
    Ind = [0]*N
    while stack:
        p = stack[-1]
        
        
        
        if Ind[p] == len(graph[p]):
            stack.pop()
            if len(stack) > 0:
                par = stack[-1]
                kiyo = Score[par] * cmb(Child[p]-1, Child[par])
                Score[p] = Score[p] * pow(kiyo, mod-2, mod) % mod
                Child[p] -= Child[par]
                Child[par] += Child[p]
                Score[par] = (Score[par] * Score[p] * cmb(Child[par]-1, Child[p])) % mod
        elif len(stack) > 1 and stack[-2] == graph[p][Ind[p]]:
            Ind[p] += 1
        else:
            ch = graph[p][Ind[p]]
            kiyo = Score[ch] * cmb(Child[p]-1, Child[ch])
            Score[p] = Score[p] * pow(kiyo, mod-2, mod) % mod
            Child[p] -= Child[ch]
            Child[ch] += Child[p]
            Score[ch] = (Score[ch] * Score[p] * cmb(Child[ch]-1, Child[p])) % mod
            ans[ch] = Score[ch]
            stack.append(ch)
            Ind[p] += 1

def main():
    dfs1(0)
    dfs2(0)
    print(*ans, sep="\n")

if __name__ == "__main__":
    main()

Solution (Python):
import sys
sys.setrecursionlimit(10**6)
def input():
	return sys.stdin.buffer.readline()[:-1]

MOD = 10**9 + 7
list_size = 200001

f_list = [1] * list_size
f_r_list = [1] * list_size

for i in range(list_size - 1):
	f_list[i + 1] = int((f_list[i] * (i + 2)) % MOD)

f_r_list[-1] = pow(f_list[-1], MOD - 2, MOD)

for i in range(2, list_size + 1):
	f_r_list[-i] = int((f_r_list[-i + 1] * (list_size + 2 - i)) % MOD)

def comb(n, r):
	if n < r:
		return 0
	elif n == 0 or r == 0 or n == r:
		return 1
	else:
		return (((f_list[n - 1] * f_r_list[n - r - 1]) % MOD) * f_r_list[r - 1]) % MOD 

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


dp_pat = [0 for _ in range(n)]
dp_num = [0 for _ in range(n)]


def dfs1(x, p):
	num = 0
	res = 1
	for v in adj[x]:
		if v == p:
			continue
		dfs1(v, x)
		num += dp_num[v]
		res *= comb(num, dp_num[v]) * dp_pat[v]
		res %= MOD
	dp_num[x] = num+1
	dp_pat[x] = res
	return

dfs1(0, -1)
ans = [0 for _ in range(n)]
ans[0] = dp_pat[0]

def dfs2(x, p):
	for v in adj[x]:
		if v == p:
			continue
		pres = [dp_pat[x], dp_num[x], dp_pat[v], dp_num[v]]
		dp_pat[x] *= pow(comb(dp_num[x]-1, dp_num[v]) * dp_pat[v], MOD-2, MOD)
		dp_pat[x] %= MOD
		dp_num[x] -= dp_num[v]

		dp_pat[v] *= comb(dp_num[x] + dp_num[v] - 1, dp_num[x]) * dp_pat[x]
		dp_pat[v] %= MOD
		dp_num[v] += dp_num[x]
		ans[v] = dp_pat[v]
		dfs2(v, x)
		dp_pat[x], dp_num[x], dp_pat[v], dp_num[v] = pres
	return

dfs2(0, -1)
print(*ans, sep="\n")

Solution (Python):

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

N = int(readline())
m = map(int, read().split())
AB = zip(m, m)

MOD = 10 ** 9 + 7

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

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

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

size_d = [0] * (N + 1)
dp_d = [1] * (N + 1)

for v in order[::-1]:
    dp_d[v] *= fact[size_d[v]]
    dp_d[v] %= MOD
    p = parent[v]
    s = size_d[v] + 1
    size_d[p] += s
    dp_d[p] *= fact_inv[s] * dp_d[v]
    dp_d[p] %= MOD

size_u = [N - 2 - x for x in size_d]
dp_u = [1] * (N + 1)

for v in order[1:]:
    p = parent[v]
    x = dp_d[p]
    x *= dp_u[p]
    x *= fact_inv[size_d[p]]
    x *= fact[size_d[v] + 1]
    x *= pow(dp_d[v], MOD - 2, MOD)
    x *= fact[size_u[v]]
    x *= fact_inv[size_u[p] + 1]
    dp_u[v] = x % MOD

for xd, xu, sd, su in zip(dp_d[1:], dp_u[1:], size_d[1:], size_u[1:]):
    su += 1
    x = xd * xu * fact[sd + su] * fact_inv[sd] * fact_inv[su] % MOD
    print(x)

Solution (Python):
import sys

sys.setrecursionlimit(10**6)
stdin = sys.stdin

ns = lambda: stdin.readline().rstrip()
ni = lambda: int(stdin.readline().rstrip())
nm = lambda: map(int, stdin.readline().split())
nl = lambda: list(map(int, stdin.readline().split()))

n_ = 2 * 10**5 + 20
mod = 10**9 + 7
fun = [1] * (n_ + 1)
for i in range(1, n_ + 1):
    fun[i] = fun[i - 1] * i % mod
rev = [1] * (n_ + 1)
rev[n_] = pow(fun[n_], mod - 2, mod)
for i in range(n_ - 1, 0, -1):
    rev[i] = rev[i + 1] * (i + 1) % mod

def modinv(x, mod):
    x %= mod
    a, b = x, mod
    u, v = 1, 0
    while b:
        t = a // b
        a -= t * b; a, b = b, a
        u -= t * v; u, v = v, u
    return u % mod

def nCr(n, r):
    if r > n:
        return 0
    return fun[n] * rev[r] % mod * rev[n - r] % mod

n = ni()
g = [list() for _ in range(n)]
for _ in range(n-1):
    a,b = nm()
    a -= 1; b -= 1
    g[a].append(b)
    g[b].append(a)

sl = [1]*n
pm = [1]*n
def dfs(v, p):
    for x in g[v]:
        if x == p:
            continue
        dfs(x, v)
        sl[v] += sl[x]
        pm[v] = pm[v] * pm[x] % mod
    sv = sl[v] - 1
    for x in g[v]:
        if x == p:
            continue
        pm[v] = pm[v] * nCr(sv, sl[x]) % mod
        sv -= sl[x]
    return

def dfs2(v, p):
    pp = pm[p] *  modinv(nCr(n-1, sl[v]) * pm[v], mod) % mod
    sp = n - sl[v]
    pm[v] = pm[v] * pp % mod * nCr(n-1, sp) % mod
    for x in g[v]:
        if x == p:
            continue
        dfs2(x, v)

dfs(0, -1)
for x in g[0]:
    dfs2(x, 0)

print(*pm, sep = '\n')

Solution (Python):



SIZE=2*10**5+5; MOD=10**9+7 

SIZE += 1
inv = [0]*SIZE  
fac = [0]*SIZE  

inv[1] = 1
fac[0] = fac[1] = 1

for i in range(2,SIZE):
    inv[i] = MOD - (MOD//i)*inv[MOD%i]%MOD
    fac[i] = fac[i-1]*i%MOD
    


import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
read = sys.stdin.read

n = int(input())
ab = [int(i)-1 for i in read().split()]

g = [[] for _ in range(n)]
M = iter(ab)
for a,b in zip(M,M):
    g[a].append(b)
    g[b].append(a)

order = []
parent = [-1]*n
q = [0]
while q:
    v = q.pop()
    order.append(v)
    for c in g[v]:
        if c != parent[v]:
            q.append(c)
            parent[c] = v
        
size = [1]*n
for i in order[n-1:0:-1]:
    size[parent[i]] += size[i]

res = fac[n]
for i in range(n):
    res *= inv[size[i]]
    res %= MOD

ans = [0]*n
ans[0] = res

for c in order[1::]:
    v = parent[c]
    ans[c] = ans[v]*size[c]%MOD*inv[n-size[c]]%MOD

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

Solution (Python):

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

N = int(readline())
m = map(int, read().split())
AB = zip(m, m)

MOD = 10 ** 9 + 7

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

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

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

size_d = [0] * (N + 1)
dp_d = [1] * (N + 1)

for v in order[::-1]:
    dp_d[v] *= fact[size_d[v]]
    dp_d[v] %= MOD
    p = parent[v]
    s = size_d[v] + 1
    size_d[p] += s
    dp_d[p] *= fact_inv[s] * dp_d[v]
    dp_d[p] %= MOD

size_u = [N - 2 - x for x in size_d]
dp_u = [1] * (N + 1)

for v in order[1:]:
    p = parent[v]
    x = dp_d[p]
    x *= dp_u[p]
    x *= fact_inv[size_d[p]]
    x *= fact[size_d[v] + 1]
    x *= pow(dp_d[v], MOD - 2, MOD)
    x *= fact[size_u[v]]
    x *= fact_inv[size_u[p] + 1]
    dp_u[v] = x % MOD

for xd, xu, sd, su in zip(dp_d[1:], dp_u[1:], size_d[1:], size_u[1:]):
    su += 1
    x = xd * xu * fact[sd + su] * fact_inv[sd] * fact_inv[su] % MOD
    print(x)