#include <bits/stdc++.h>
using ul = std::uint32_t;
using li = std::int32_t;
using ull = std::uint64_t;
using ll = std::int64_t;
using llf = long double;
const ul maxn = 5e5;
const ul base = 1e9 + 7;
ul mul(ul a, ul b) { return ull(a) * ull(b) % base; }
ul n;
std::vector<ul> edge[maxn + 1];
ul fa[maxn + 1];
ul depth[maxn + 1];
void search(ul curr, ul prev) {
  for (ul nex : edge[curr]) {
    if (nex == prev) {
      continue;
    }
    fa[nex] = curr;
    depth[nex] = depth[curr] + 1;
    search(nex, curr);
  }
}
ul deg[maxn + 1];
std::map<ul, ul> ex[maxn + 1];
ul vis[maxn + 1];
ul way[maxn + 1];
ul invway[maxn + 1];
int main() {
  std::scanf("%u", &n);
  for (ul i = 1; i <= n - 1; ++i) {
    ul u, v;
    std::scanf("%u%u", &u, &v);
    edge[u].push_back(v);
    edge[v].push_back(u);
    ++deg[u];
    ++deg[v];
  }
  search(1, 0);
  for (ul t = 1; t <= n; ++t) {
    ul s;
    std::scanf("%u", &s);
    if (s == t) {
      std::printf("0\n");
      return 0;
    }
    if (!s) {
      continue;
    }
    ul tot = 0;
    ul invtot = 0;
    ul a, b;
    for (a = s, b = t; a != b;) {
      if (depth[a] > depth[b]) {
        ++tot;
        way[tot] = a;
        a = fa[a];
      } else {
        ++invtot;
        invway[invtot] = b;
        b = fa[b];
      }
    }
    ++tot;
    way[tot] = a;
    for (; invtot; --invtot) {
      ++tot;
      way[tot] = invway[invtot];
    }
    ex[way[1]][way[1]] = way[2];
    for (ul i = 2; i != tot; ++i) {
      auto& tmp = ex[way[i]][way[i - 1]];
      if (tmp) {
        std::printf("0\n");
        return 0;
      }
      tmp = way[i + 1];
    }
    ex[way[tot]][way[tot - 1]] = way[tot];
    for (ul i = 1; i <= tot; ++i) {
      --deg[way[i]];
    }
  }
  ul ans = 1;
  ul tim;
  for (ul i = 1; i <= n; ++i) {
    while (ex[i].size()) {
      ul cnt = 0;
      auto j = ex[i].begin();
      ++tim;
      for (; j != ex[i].end();) {
        ++cnt;
        if (vis[j->second] == tim) {
          if (cnt != edge[i].size() + 1) {
            std::printf("0\n");
            return 0;
          } else {
            ex[i].erase(j);
            break;
          }
        } else {
          vis[j->first] = tim;
          auto tmp = ex[i].find(j->second);
          ex[i].erase(j);
          j = tmp;
        }
      }
    }
    if (!~deg[i]) {
      continue;
    }
    for (ul j = 1; j <= deg[i]; ++j) {
      ans = mul(j, ans);
    }
  }
  std::printf("%u\n", ans);
  return 0;
}
