Problem:
 Score : 100 points    Problem Statement There is a tree with N vertices, numbered 1, 2, \ldots, N .
For each i ( 1 \leq i \leq N - 1 ), the i -th edge connects Vertex x_i and y_i .  Taro has decided to paint each vertex in white or black.
Here, it is not allowed to paint two adjacent vertices both in black.  Find the number of ways in which the vertices can be painted, modulo 10^9 + 7 .      Constraints  All values in input are integers.  1 \leq N \leq 10^5  1 \leq x_i, y_i \leq N  The given graph is a tree.         Input Input is given from Standard Input in the following format:  N  x_1  y_1  x_2  y_2  :  x_{N - 1}  y_{N - 1}       Output Print the number of ways in which the vertices can be painted, modulo 10^9 + 7 .        Sample Input 1 3
1 2
2 3      Sample Output 1 5  There are five ways to paint the vertices, as follows:        Sample Input 2 4
1 2
1 3
1 4      Sample Output 2 9  There are nine ways to paint the vertices, as follows:        Sample Input 3 1      Sample Output 3 2       Sample Input 4 10
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7      Sample Output 4 157

Solution (Python):
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop,heapify
import math
from collections import *
from functools import reduce,cmp_to_key
import sys
input = sys.stdin.readline

from itertools import accumulate
from functools import lru_cache

M = mod = 10 ** 9 + 7
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)
 
def li():return [int(i) for i in input().rstrip('\n').split()]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def li2():return [i for i in input().rstrip('\n')]
def li3():return [int(i) for i in input().rstrip('\n')]
 



sys.setrecursionlimit(10 ** 6)

g = 0
@lru_cache(None)
def dp(i, par = -1, black = 0):
    global g
    ans = 1
    nokids = 1
    if black:
        for j in g[i]:
            if j != par:
                nokids = 0
                ans = ans * dp(j, i, 0) % mod
    else:
        for j in g[i]:
            if j != par:
                nokids = 0
                ans = ( ans * (dp(j, i, 0) + dp(j, i, 1)) ) % mod

    if nokids:ans = 1
    return ans



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

l = []
for _ in range(n - 1):
    a, b = li()
    g[a].append(b)
    g[b].append(a)


root = 1    
ans = dp(root, -1, 0) + dp(root, -1, 1)

print(ans % mod)

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

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

def dfs(start):
  stack = [start]
  parent = [N]*N
  parent[start] = -1
  white, black = [1]*N, [1]*N
  while stack:
    v = stack[-1]
    marker = 0
    for u in edge[v]:
      if u==parent[v]:
        continue
      if parent[u]==N: 
        marker = 1
        parent[u]=v
        stack.append(u)
      else: 
        white[v] *= white[u]+black[u]
        white[v] %= mod
        black[v] *= white[u]
        black[v] %= mod
    if marker==0:
      stack.pop()
  ans = (black[0]+white[0])%mod
  return ans

mod = 10**9+7
ans = dfs(0)
print(ans)

Solution (Python):
from collections import deque
import sys
sys.setrecursionlimit(10**9)
n=int(input())
g=[[] for i in range(n)]
for i in range(n-1):
    a,b=map(int,input().split())
    a-=1
    b-=1
    g[a].append(b)
    g[b].append(a)
q=deque([0])
v=[0]*n
v[0]=1
gp=[[] for i in range(n)]
while q:
    p=q.popleft()
    for i in g[p]:
        if v[i]==0:
            v[i]=1
            gp[p].append(i)
            q.append(i)
MOD=10**9+7
flag=[0]*n
dp=[[0,0] for i in range(n)]
def f(i):
    if flag[i]:
        return 0
    flag[i]=1
    dp[i][0]=1
    dp[i][1]=1
    for j in gp[i]:
        f(j)
        dp[i][0]=dp[i][0]*(dp[j][0]+dp[j][1])%MOD
        dp[i][1]=dp[i][1]*dp[j][0]
        dp[i][0]%=MOD
        dp[i][1]%=MOD
    return 0
f(0)
print((dp[0][0]+dp[0][1])%MOD)

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**8)
MOD = 10**9+7

N = int(input())
XY = [tuple(map(int,input().split())) for i in range(N-1)]
es = [[] for _ in range(N)]
for x,y in XY:
    x,y = x-1,y-1
    es[x].append(y)
    es[y].append(x)

dp = [[1,1] for i in range(N)]
def rec(v,p=-1):
    for to in es[v]:
        if to==p: continue
        rec(to,v)
        dp[v][0] *= (dp[to][0] + dp[to][1])
        dp[v][1] *= dp[to][0]
        dp[v][0] %= MOD
        dp[v][1] %= MOD
rec(0)

print(sum(dp[0]) % MOD)

Solution (Python):

def countSetBits(n):
    count = 0
    while (n):
        n &= (n - 1)
        count += 1

    return count


import sys
sys.setrecursionlimit(10**6)


N=10**9 + 7
n=int(input())
g=[[] for _ in range(n+5)]
for _ in range(n-1):
    a,b=map(int,input().strip().split(" "))
    g[a-1].append(b-1)
    g[b-1].append(a-1)
dpr=[-1 for _ in range(n+5)]
dpb=[-1 for _ in range(n+5)]

def dfs(v,p):
    if dpr[v]!=-1:
        return
    if len(g[v])==1 and g[v][0]==p:
        dpr[v]=1
        dpb[v]=1
        return
    valr=1
    valb=1
    for c in g[v]:
        if c==p:
            continue
        dfs(c,v)
        valr=(valr*((dpr[c]+dpb[c])%N))%N
        valb=(valb*(dpr[c]))%N
    dpr[v]=valr
    dpb[v]=valb
    return
dfs(0,-1)
print((dpr[0]+dpb[0])%N)

Solution (Python):
import sys
sys.setrecursionlimit(10**9)

MOD = 10**9 + 7
N = int(input())
paths = {i:[] for i in range(N+1)}
for _ in range(N-1):
    x, y = map(int, input().split())
    paths[x].append(y)
    paths[y].append(x)

dpt = [[-1] * 2 for i in range(N+1)]

def count_cc(prev, node, color):
    if dpt[node][color] != -1:
        return dpt[node][color]
    if paths[node] == [prev]:
        dpt[node][color] = 1
        return 1
    result = 1
    if color == 0:
        for nxt in paths[node]:
            if nxt == prev:
                continue
            result *= (count_cc(node, nxt, 0) + count_cc(node, nxt, 1))
            result %= MOD
    else:
        for nxt in paths[node]:
            if nxt == prev:
                continue
            result *= count_cc(node, nxt, 0)
            result %= MOD

    dpt[node][color] = result
    return result

print((count_cc(0, 1, 0) + count_cc(0, 1, 1)) % MOD)

Solution (Python):




from collections import deque

N=int(input())
G=[[] for _ in range(N)]
mod = 10**9+7

for i in range(N-1):
  x,y=map(int,input().split())
  G[x-1].append(y-1)
  G[y-1].append(x-1)
  
dp = [[0]*2 for _ in range(N)]

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


for a in R[::-1]:
  
  if len(G[a])==0:
    dp[a][0] = 1
    dp[a][1] = 1
  
  elif len(G[a])>1:
    
    dp[a][0] = 1
    dp[a][1] = 1
    for c in G[a]:
      dp[a][1] *= sum(dp[c]) 
      dp[a][0] *= dp[c][1] 
    dp[a][0] %= mod
    dp[a][1] %= mod
  b = P[a]
  if b == -1:break
  dp[b][0] += dp[a][1] % mod
  dp[b][1] += dp[a][0]+dp[a][1] % mod

print(sum(dp[0])%mod)

Solution (Python):
import sys
sys.setrecursionlimit(10 ** 6)





N = int(input())
G = [[] for i in range(N)]
MOD = 10 ** 9 + 7

for i in range(N - 1):
  x,y = map(int,input().split())
  G[x - 1].append(y - 1)
  G[y - 1].append(x - 1)
  
dp_black = [-1] * N
dp_white = [-1] * N


def search(v,parent):
  if dp_black[v] != -1:
    return (dp_black[v],dp_white[v])
  black = 1
  white = 1
  for child in G[v]:
    if child == parent:
      continue
    b,w = search(child, v)
    black *= w
    black %= MOD
    white *= (b + w)
    white %= MOD
  dp_black[v] = black
  dp_white[v] = white
  return (black, white)

print(sum(search(0, -1)) % MOD)

Solution (Python):
import sys
sys.setrecursionlimit(10 ** 6)





N = int(input())
G = [[] for i in range(N)]
MOD = 10 ** 9 + 7

for i in range(N - 1):
  x,y = map(int,input().split())
  G[x - 1].append(y - 1)
  G[y - 1].append(x - 1)
  
dp_black = [-1] * N
dp_white = [-1] * N


def search(v,parent):
  if dp_black[v] != -1:
    return (dp_black[v],dp_white[v])
  black = 1
  white = 1
  for child in G[v]:
    if child == parent:
      continue
    b,w = search(child, v)
    black *= w
    black %= MOD
    white *= (b + w)
    white %= MOD
  dp_black[v] = black
  dp_white[v] = white
  return (black, white)

print(sum(search(0, -1)) % MOD)

Solution (Python):
MOD = 10**9 + 7


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

    dp_w = [0]*N
    dp_b = [0]*N

    def dfs(s):
        seen = [False]*N
        par = [-1]*N
        stack = [s]
        seen[s] = True
        while stack:
            v = stack.pop()
            if v >= 0:
                stack.append(~v)
                for u in G[v]:
                    if seen[u]:
                        continue
                    stack.append(u)
                    seen[u] = True
                    par[u] = v
            else:
                
                
                v = ~v
                w = 1
                b = 1
                for u in G[v]:
                    if u == par[v]:
                        continue
                    w *= dp_w[u] + dp_b[u]
                    b *= dp_w[u]
                    w %= MOD
                    b %= MOD
                dp_w[v] += w
                dp_b[v] += b
                dp_w[v] %= MOD
                dp_b[v] %= MOD

    dfs(0)
    print((dp_w[0] + dp_b[0]) % MOD)


if __name__ == '__main__':
    main()

Solution (Python):






import sys
input = sys.stdin.readline

import math

import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache





MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"






def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]


def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()


def DD(arg): return defaultdict(arg)


def inv(n): return pow(n, MOD-2, MOD)


kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret


def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr


def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors


def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum


def gcd(a, b):
    while b: a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd (a, b)


def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count


def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]


def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count




N = I()
order = []
to = [[] for i in range(N)]

def bfs(graph, start):
  N = len(graph)
  d = [INF] * N
  d[start] = 0
  q = deque([start])
  while q:
    u = q.popleft()
    order.append(u)
    for v in graph[u]:
      if d[v] != INF: continue
      d[v] = d[u] + 1
      to[u].append(v)
      q.append(v)
  return d

graph = [[] for i in range(N)]
for _ in range(N-1):
  a,b = IL()
  graph[a-1].append(b-1)
  graph[b-1].append(a-1)
bfs(graph,0)

dp = [[0,0] for i in range(N)]

for i in order[::-1]:
  if not to[i]:
    dp[i] = [1,1]
  else:
    temp1 = 1
    temp2 = 1
    for j in to[i]:
      temp1 *= sum(dp[j])
      temp1 %= MOD
      temp2 *= dp[j][1]
      temp2 %= MOD
    dp[i] = [temp2%MOD,temp1%MOD]
print(sum(dp[0])%MOD)

Solution (Python):
from sys import stdin
import sys
import math
from functools import reduce
import functools
import itertools
from collections import deque,Counter,defaultdict
from operator import mul
import copy


import heapq
sys.setrecursionlimit(10**6)
INF =  float("inf")
import bisect
import statistics
mod = 10**9+7

N = int(input())
al = [[] for i in range(N+1)]

for i in range(N-1):
    a, b = list(map(int, input().split()))

    al[a].append(b)
    al[b].append(a)

b = [0 for i in range(N + 1)]
w = [0 for i in range(N + 1)]
seen = [0 for i in range(N + 1)]

@functools.lru_cache(None)
def bfs(u):
    seen[u] = 1

    b[u] = 1
    w[u] = 1

    for v in al[u]:
        if seen[v] == 0:
            seen[v] = 1
            bfs(v)
            b[u] = (b[u] * w[v]) % mod
            w[u] = (w[u] * ((b[v] + w[v]) % mod)) % mod

bfs(1)

print((b[1] + w[1]) % mod)

Solution (Python):
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from bisect import bisect_right, bisect_left
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, gamma, log
from operator import mul
from functools import reduce
from copy import deepcopy

sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): pass
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7

n = I()
G = [[] for _ in range(n)]
for _ in range(n - 1):
    x, y = LI()
    G[x - 1] += [y - 1]
    G[y - 1] += [x - 1]


par = [-1] * n
def f(u):
    b, w = 1, 1
    for v in G[u]:
        if v == par[u]:
            continue
        par[v] = u
        cb, cw = f(v)
        b = b * cw % mod
        w = w * (cw + cb)
    return b, w

bb, ww = f(0)
print((bb + ww) % mod)

Solution (Python):

import sys 
sys.setrecursionlimit(10**6)
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
MOD = 10**9+7

N = int(readline())
edge = [[] for _ in range(N+1)]
for i in range(N-1):
    x,y = map(int,readline().split())
    edge[x].append(y)
    edge[y].append(x)



def dfs(x,par):
    total,white = 1,1
    for y in edge[x]:
        if y == par:
            continue
        w,t = dfs(y,x)
        total *= w; total%=MOD
        white *= t; white%=MOD
    total += white
    total %= MOD
    return white,total


print(dfs(1,0)[1])

Solution (Python):
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10 ** 5 + 1)

N = int(readline())
G = [[] for i in range(N)]

for i in range(N - 1):
  x,y = map(int,readline().split())
  G[x - 1].append(y - 1)
  G[y - 1].append(x - 1)

DIV = 10 ** 9 + 7






dp = [[-1] * 2 for i in range(N)]

def search_black(X, parent): 
  if dp[X][1] != -1:
    return dp[X][1]
  
  children = G[X]
  if len(children) == 1 and children[0] == parent:
    dp[X][1] = 1
    return 1
  ans = 1
  for child in children:
    if child == parent:
      continue
    ans *= search_white(child, X)
    ans %= DIV
  dp[X][1] = ans
  return ans
  
def search_white(X, parent): 
  if dp[X][0] != -1:
    return dp[X][0]
  
  children = G[X]
  if len(children) == 1 and children[0] == parent:
    dp[X][0] = 1
    return 1
  ans = 1
  for child in children:
    if child == parent:
      continue
    ans *= (search_white(child, X) + search_black(child, X))
    ans %= DIV
  dp[X][0] = ans
  return ans
  
print((search_white(0, -1) + search_black(0, -1)) % DIV)

Solution (Python):
from sys import stdin, stdout, setrecursionlimit
from collections import deque, defaultdict, Counter
from heapq import heappush, heappop
from functools import lru_cache
import math

setrecursionlimit(10**6)
rl = lambda: stdin.readline()
rll = lambda: stdin.readline().split()
rli = lambda: map(int, stdin.readline().split())
rlf = lambda: map(float, stdin.readline().split())

INF, NINF = float('inf'), float('-inf')

def main():
	MOD = 10**9 + 7
	n = int(rl())
	G = [[] for _ in range(n)]
	for _ in range(n-1):
		u, v = rli()
		u -= 1
		v -= 1
		G[u].append(v)
		G[v].append(u)


	wb = [[1,1] for _ in range(n+1)]
	wb[n] = [0, 0]
	seen = [0 for _ in range(n)]
	stack = []
	stack.append((0, n))
	while stack:
		node, prnt = stack.pop()
		w, b = wb[node]
		if not seen[node]:
			seen[node] = 1
			stack.append((node, prnt))
			for nbhr in G[node]:
				if nbhr == prnt: continue
				stack.append((nbhr, node))
		else:
			pw, pb = wb[prnt]
			pw *= (w + b)
			pb *= w 
			wb[prnt] = [pw % MOD, pb % MOD]

	ans = (wb[0][0] + wb[0][1]) % MOD
	print(ans)
	stdout.close()

if __name__ == "__main__":
	main()

Solution (Python):
from sys import stdin, stdout, setrecursionlimit
from collections import deque, defaultdict, Counter
from heapq import heappush, heappop
from functools import lru_cache
import math

setrecursionlimit(10**6)
rl = lambda: stdin.readline()
rll = lambda: stdin.readline().split()
rli = lambda: map(int, stdin.readline().split())
rlf = lambda: map(float, stdin.readline().split())

INF, NINF = float('inf'), float('-inf')

def main():
	MOD = 10**9 + 7
	n = int(rl())
	G = [[] for _ in range(n)]
	for _ in range(n-1):
		u, v = rli()
		u -= 1
		v -= 1
		G[u].append(v)
		G[v].append(u)

	def dfs(node, prnt):
		w, b = 1, 1
		for nbhr in G[node]:
			if nbhr == prnt: continue
			nw, nb = dfs(nbhr, node)
			w *= (nw + nb)
			w %= MOD
			b *= nw 
			b %= MOD
		return w, b

	answ, ansb = dfs(0, -1)
	print((answ + ansb) % MOD)

	stdout.close()

if __name__ == "__main__":
	main()

Solution (Python):
import sys
sys.setrecursionlimit(10**8)

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

def dfs(v,mod):
  black,white = 1,1
  for u in edge[v]:
    if visited[u]==False:
      visited[u]=True
      b,w = dfs(u,mod)
      black *= w
      white *= b+w
  black %= mod
  white %= mod
  return black,white

mod = 10**9+7
visited = [False]*N
visited[0]=True
black,white = dfs(0,mod)
print((black+white)%mod)

Solution (Python):
import sys
sys.setrecursionlimit(10**7)
n=int(input())
if n==1:
    print(2)
    exit()
edge=[[] for _ in range(n)]
for _ in range(n-1):
    x,y=map(int,input().split())
    x-=1
    y-=1
    edge[x].append(y)
    edge[y].append(x)
dp=[[0]*2 for _ in range(n)]
mod=10**9+7
def dfs(s,prev):
    if edge[s]==[prev]:
        dp[s][0]=1
        dp[s][1]=1
        return
    w=1
    b=1
    for c in edge[s]:
        if c==prev:
            continue
        dfs(c,s)
        w=w*(dp[c][0]+dp[c][1])%mod
        b=b*dp[c][0]%mod
    dp[s][0]=w
    dp[s][1]=b
    return
dfs(0,-1)
print(sum(dp[0])%mod)

Solution (Python):
import sys
import re
import math
import collections
import decimal
import bisect
import itertools
import fractions
import functools
import copy
import heapq
import decimal
import statistics
import queue



sys.setrecursionlimit(10 ** 9)
INF = 10 ** 16
MOD = 10 ** 9 + 7


ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))




def main():
    n = ni()
    e = [[] for _ in range(n)]
    for _ in range(n - 1):
        x, y = ns()
        x -= 1
        y -= 1
        e[x].append(y)
        e[y].append(x)

    
    
    dp = [[1, 1] for _ in range(n)]
    visited = [False for _ in range(n)]

    def dfs(vi, prnt):
        if visited[vi]:
            return
        visited[vi] = True

        for chld in e[vi]:
            if chld == prnt:
                continue
            dfs(chld, vi)

            
            dp[vi][0] *= dp[chld][0] + dp[chld][1]
            dp[vi][0] %= MOD
            
            dp[vi][1] *= dp[chld][0]
            dp[vi][1] %= MOD

    dfs(0, -1)
    print((dp[0][0] + dp[0][1]) % MOD)


if __name__ == '__main__':
    main()

Solution (Python):
import sys
sys.setrecursionlimit(10 ** 7)
inp = sys.stdin.buffer.readline


def resolve():
    MOD = 10 ** 9 + 7

    n = int(inp())
    e = [[] for _ in range(n)]
    for _ in range(n - 1):
        x, y = map(lambda x: int(x) - 1, inp().split())
        e[x].append(y)
        e[y].append(x)

    
    
    dp = [[1, 1] for _ in range(n)]
    visited = [False for _ in range(n)]

    def dfs(vi, prnt):
        
        
        visited[vi] = True

        for chld in e[vi]:
            if chld == prnt or visited[chld]:
                continue
            dfs(chld, vi)

            
            dp[vi][0] *= (dp[chld][0] + dp[chld][1]) % MOD
            dp[vi][0] %= MOD
            
            dp[vi][1] *= dp[chld][0] % MOD
            dp[vi][1] %= MOD

    dfs(0, -1)
    print((dp[0][0] + dp[0][1]) % MOD)


if __name__ == "__main__":
    resolve()

Solution (Python):
import sys
sys.setrecursionlimit(10**6)

mod=10**9+7
def dfs(v):
  if checked[v]==1:
    return
  checked[v]=1
  dp[v][0]=1
  dp[v][1]=1
  for u in g[v]:
    if checked[u]==0:
      dfs(u)
      dp[v][0]=(dp[v][0]*(dp[u][0]+dp[u][1]))%mod
      dp[v][1]=(dp[v][1]*dp[u][0])%mod

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)
dp=[[0,0] for _ in range(n+1)]
checked=[0]*(n+1)
dfs(1)
print((dp[1][0]+dp[1][1])%mod)