#include <bits/stdc++.h>
using namespace std;
const int m = 1e9 + 7;
bool vis[100005];
vector<int> tr[100005];
map<pair<int, int>, int> ma;
long long ans = 0;
int k;
long long po(long long a, long long n) {
  long long ret = 1;
  while (n) {
    if (n & 1) ret = (ret * a) % m;
    a = (a * a) % m;
    n >>= 1;
  }
  return ret;
}
int dfs(int x) {
  vis[x] = 1;
  int child = 0;
  for (auto i : tr[x]) {
    if (!vis[i]) {
      if (ma[{x, i}]) {
        int ch = dfs(i);
        ans -= po(ch, k);
        ans %= m;
        if (ans < 0) ans += m;
      } else
        child += dfs(i);
    }
  }
  return child + 1;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int n;
  cin >> n >> k;
  for (int i = 1; i < n; ++i) {
    int u, v, c;
    cin >> u >> v >> c;
    tr[u].push_back(v);
    tr[v].push_back(u);
    ma[{u, v}] = ma[{v, u}] = c;
  }
  ans = po(n, k);
  ans %= m;
  memset(vis, 0, sizeof vis);
  int tmp = dfs(1);
  ans -= po(tmp, k);
  ans %= m;
  if (ans < 0) ans += m;
  cout << ans;
}
