#include <bits/stdc++.h>
using namespace std;
vector<pair<long long, long long> > adj[200002];
bool visited[200002];
long long nPk(long long n, long long k) {
  if (k == 0) return 1;
  long long prod = 1;
  for (long long i = 1; i <= k; i++) {
    prod = (prod * n) % 1000000007;
  }
  return prod;
}
void dfs(long long s, long long &temp) {
  visited[s] = true;
  for (long long i = 0; i < adj[s].size(); i++) {
    if (adj[s][i].second == 1) continue;
    if (!visited[adj[s][i].first]) {
      dfs(adj[s][i].first, ++temp);
    }
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long n, k;
  cin >> n >> k;
  for (long long i = 0; i < n - 1; i++) {
    long long a, b, c;
    cin >> a >> b >> c;
    adj[a].push_back(make_pair(b, c));
    adj[b].push_back(make_pair(a, c));
  }
  for (long long i = 1; i <= n; i++) visited[i] = false;
  long long ans = 0;
  for (long long i = 1; i <= n; i++) {
    long long temp = 1;
    if (!visited[i]) {
      dfs(i, temp);
      long long tans;
      tans = nPk(temp, k);
      ans = (ans + tans) % 1000000007;
    }
  }
  long long asd = nPk(n, k);
  long long res = ((asd - ans) + 1000000007) % 1000000007;
  cout << res << endl;
  return 0;
}
