#include <bits/stdc++.h>
using namespace std;
vector<long long> adj[100005];
bool vis[100005];
long long power(long long x, long long y, long long p) {
  long long res = 1;
  x = x % p;
  while (y > 0) {
    if (y & 1) res = (res * x) % p;
    y = y >> 1;
    x = (x * x) % p;
  }
  return res;
}
long long cnt1 = 0;
map<pair<long long, long long>, long long> mpp;
void dfs(long long val) {
  vis[val] = true;
  cnt1++;
  for (auto& i : adj[val]) {
    if (!vis[i] && (mpp[{i, val}] == 0 && mpp[{val, i}] == 0)) {
      dfs(i);
    }
  }
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long n, k, mod = 1e9 + 7, x, y, z, ans;
  cin >> n >> k;
  for (long long i = 0; i < n - 1; i++) {
    cin >> x >> y >> z;
    adj[x].push_back(y);
    adj[y].push_back(x);
    mpp[{x, y}] = z;
    mpp[{y, x}] = z;
  }
  ans = power(n, k, mod);
  for (long long i = 1; i <= n; i++) {
    if (!vis[i]) {
      cnt1 = 0;
      dfs(i);
      ans -= power(cnt1, k, mod);
      while (ans < 0) ans += mod;
    }
  }
  cout << ans;
  return 0;
}
