DFS遍历整棵树,记录每个节点到所有左右子树叶子节点的距离。
dist[i][j][k] 表示第i个节点左子树(j = 0)或右子树(j = 1)距离为k的叶子节点个数
最后用双指针计算每个节点满足条件的叶子对。
算法复杂度O(n*distance)
class Solution {
public:
int dist[1100][2][15];
int cnt = 0;
void dfs(TreeNode* node, int father, bool isRight){
if (!node) return;
cnt++;
int idx = cnt;
dfs(node->left, idx, 0);
dfs(node->right, idx, 1);
//judge leaf node
if (!node->left && !node->right) dist[idx][0][0]++;
for (int i = 0; i<=10; i++)
dist[father][isRight][i+1] = dist[idx][0][i] + dist[idx][1][i];
}
int countPairs(TreeNode* root, int distance) {
memset(dist, 0, sizeof dist);
dfs(root, 0, 0);
int ans = 0;
for (int i = 1; i<=cnt; i++){
int sum = 0;
for (int j = distance - 1, k = 1; j >=1; j--, k++){
sum += dist[i][1][k];
ans += dist[i][0][j] * sum;
}
}
return ans;
}
};