#include <bits/stdc++.h>
using namespace std;
int main() {
  long long int N, M;
  cin >> N >> M;
  vector<vector<long long int> > vect(N + 1);
  long long int a, b, c, i, j, k;
  for (i = 1; i < N; i++) {
    cin >> a >> b >> c;
    vect[a].push_back(b);
    vect[a].push_back(c);
    vect[b].push_back(a);
    vect[b].push_back(c);
  }
  queue<long long int> q;
  bool x[N + 1];
  memset(x, false, sizeof(x));
  long long int count = 0;
  vector<long long int> vect1;
  for (i = 1; i <= N; i++) {
    if (x[i] == false) {
      q.push(i);
      x[i] = true;
      count = 1;
      while (q.size() > 0) {
        a = q.front();
        q.pop();
        for (j = 0; j < vect[a].size(); j += 2) {
          if ((vect[a][j + 1] == 0) && (x[vect[a][j]] == false)) {
            q.push(vect[a][j]);
            x[vect[a][j]] = true;
            count++;
          }
        }
      }
      vect1.push_back(count);
    }
  }
  long long int ans = 1;
  for (i = 1; i <= M; i++) {
    ans = (ans * N) % 1000000007;
    ;
  }
  a = 0;
  for (i = 0; i < vect1.size(); i++) {
    b = 1;
    for (j = 1; j <= M; j++) {
      b = (b * vect1[i]) % 1000000007;
      ;
    }
    a = (a + b) % 1000000007;
    ;
  }
  ans = ans - a;
  if (ans < 0) {
    ans += 1000000007;
    ;
  }
  cout << ans;
  return 0;
}
