#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > t[100001];
int visit[100001];
int go(int now) {
  if (visit[now]) return 0;
  visit[now] = 1;
  int sum = 1;
  for (int i = 0; i < t[now].size(); i++) {
    if (t[now][i].second == 0) sum += go(t[now][i].first);
  }
  return sum;
}
const unsigned long long mod = 1000000007;
unsigned long long n_k(unsigned long long n, unsigned long long k) {
  unsigned long long now = 1;
  for (int i = 0; i < k; i++) {
    now = now * (n % mod);
    now %= mod;
  }
  return now;
}
int main() {
  ios_base::sync_with_stdio(0);
  int n, k, u, v, x;
  cin >> n >> k;
  for (int i = 0; i < n - 1; i++) {
    cin >> u >> v >> x;
    t[u].push_back({v, x});
    t[v].push_back({u, x});
  }
  unsigned long long ans = 1;
  unsigned long long onlyRed = 0;
  ans = n_k(n, k);
  for (int i = 1; i <= n; i++) {
    if (!visit[i]) {
      unsigned long long sum = 0;
      sum = go(i);
      onlyRed = onlyRed + (n_k(sum, k) % mod);
      onlyRed %= mod;
    }
  }
  cout << (ans - onlyRed + mod) % mod;
}
