#include <bits/stdc++.h>
using namespace std;
long long n, k, i, j, x, rez, nr, y, ok, md = 1000000007;
long long z[100005];
struct per {
  long long x, t;
} s;
vector<per> ad[100005];
deque<per> q;
int main() {
  cin >> n >> k;
  for (i = 1; i < n; i++) {
    cin >> x >> y >> j;
    ad[x].push_back({y, j});
    ad[y].push_back({x, j});
    if (j == 1) ok = 1;
  }
  rez = 1;
  for (i = 1; i <= k; i++) rez = rez * n % md;
  q.push_back({1, 0});
  z[s.x] = 1;
  while (!q.empty()) {
    s = q.front();
    q.pop_front();
    z[s.x] = 1;
    if (s.t == 0)
      nr++;
    else {
      long long sc = 1;
      for (i = 1; i <= k; i++) sc = sc * nr % md;
      rez -= sc;
      if (rez < 0) rez += md;
      nr = 1;
    }
    for (auto i : ad[s.x]) {
      if (z[i.x] == 0) {
        z[i.x] = 1;
        if (i.t == 0)
          q.push_front(i);
        else
          q.push_back(i);
      }
    }
  }
  if (nr) {
    long long sc = 1;
    for (i = 1; i <= k; i++) sc = sc * nr % md;
    rez -= sc;
    if (rez < 0) rez += md;
  }
  if (ok == 0) rez = 0;
  cout << rez << "\n";
}
