给你二叉树的根节点 root 和一个整数 distance 。
如果二叉树中两个 叶 节点之间的 最短路径长度 小于或者等于 distance ,那它们就可以构成一组 好叶子节点对 。
返回树中 好叶子节点对的数量 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-good-leaf-nodes-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public int countPairs(TreeNode root, int distance) {
Pair pair = dfs(root, distance);
return pair.count;
}
public Pair dfs(TreeNode root, int distance) {
int[] depths = new int[distance + 1];
if (root == null) {
return new Pair(depths, 0);
}
if (root.left == null && root.right == null) {
depths[0] = 1;
return new Pair(depths, 0);
}
Pair left = dfs(root.left, distance);
Pair right = dfs(root.right, distance);
for (int i = 0; i < distance; i++) {
depths[i + 1] += left.depths[i] + right.depths[i];
}
int cnt = 0;
for (int i = 0; i <= distance; i++) {
for (int j = 0; j + i + 2 <= distance; j++) {
cnt += left.depths[i] * right.depths[j];
}
}
return new Pair(depths, cnt + left.count + right.count);
}
}
class Pair {
int[] depths;
int count;
public Pair(int[] depths, int count) {
this.depths = depths;
this.count = count;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}