1,问题描述
1530. 好叶子节点对的数量
难度:中等
给你二叉树的根节点 root
和一个整数 distance
。
如果二叉树中两个 叶 节点之间的 最短路径长度 小于或者等于 distance
,那它们就可以构成一组 好叶子节点对 。
返回树中 好叶子节点对的数量 。
示例 1:

1 2 3
| 输入:root = [1,2,3,null,4], distance = 3 输出:1 解释:树的叶节点是 3 和 4 ,它们之间的最短路径的长度是 3 。这是唯一的好叶子节点对。
|
示例 2:

1 2 3
| 输入:root = [1,2,3,4,5,6,7], distance = 3 输出:2 解释:好叶子节点对为 [4,5] 和 [6,7] ,最短路径长度都是 2 。但是叶子节点对 [4,6] 不满足要求,因为它们之间的最短路径长度为 4 。
|
示例 3:
1 2 3
| 输入:root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3 输出:1 解释:唯一的好叶子节点对是 [2,5] 。
|
示例 4:
1 2
| 输入:root = [100], distance = 1 输出:0
|
示例 5:
1 2
| 输入:root = [1,1,1], distance = 2 输出:1
|
提示:
tree
的节点数在 [1, 2^10]
范围内。
- 每个节点的值都在
[1, 100]
之间。
1 <= distance <= 10
2,初步思考
理解了,但是还没有自己亲自写一遍——2025.03.21
3,代码处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| import support.TreeNode;
public class _1530好叶子节点对的数量 {
public int countPairs(TreeNode root, int distance) { Pair pair = dfs(root, distance); return pair.count; }
private Pair dfs(TreeNode root, int distance) { int[] depths = new int[distance + 1]; boolean isLeaf = root.left == null && root.right == null; if (isLeaf) { depths[0] = 1; return new Pair(depths, 0); }
int[] leftDepths = new int[distance + 1]; int[] rightDepths = new int[distance + 1]; int leftCount = 0, rightCount = 0; if (root.left != null) { Pair leftPair = dfs(root.left, distance); leftDepths = leftPair.depths; leftCount = leftPair.count; } if (root.right != null) { Pair rightPair = dfs(root.right, distance); rightDepths = rightPair.depths; rightCount = rightPair.count; }
for (int i = 0; i < distance; i++) { depths[i + 1] += leftDepths[i]; depths[i + 1] += rightDepths[i]; }
int cnt = 0; for (int i = 0; i <= distance; i++) { for (int j = 0; j + i + 2 <= distance; j++) { cnt += leftDepths[i] * rightDepths[j]; } } return new Pair(depths, cnt + leftCount + rightCount); }
class Pair { int[] depths; int count;
public Pair(int[] depths, int count) { this.depths = depths; this.count = count; } } }
|