#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 7;
long long r;
vector<vector<int>> g(100010);
vector<vector<int>> w(100010);
bool used[1000100];
void dfs(int x) {
  r++;
  used[x] = true;
  for (int i = 0; i < g[x].size(); i++) {
    if (!used[g[x][i]] && !w[x][i]) dfs(g[x][i]);
  }
}
int main() {
  long long n, k, u, v, b;
  cin >> n >> k;
  for (int i = 0; i < n - 1; i++) {
    cin >> u >> v >> b;
    g[u].emplace_back(v);
    g[v].emplace_back(u);
    w[u].emplace_back(b);
    w[v].emplace_back(b);
  }
  long long mr = 0;
  for (int i = 1; i <= n; i++)
    if (!used[i]) {
      r = 0;
      dfs(i);
      long long ss = r;
      r = 1;
      for (int j = 0; j < k; j++) r = (ss * r) % INF;
      mr = (mr + r) % INF;
    }
  long long h = n;
  n = 1;
  for (int i = 0; i < k; i++) n = (n * h) % INF;
  h = n - mr;
  while (h < 0) h += INF;
  cout << h % INF << endl;
  return 0;
}
