1530. Number of Good Leaf Nodes Pairs
MediumView on LeetCode
Time: O(n * distance²)
Space: O(n)
Advertisement
Intuition
Count pairs of good nodes (distance > k). DFS returning list of depths. Count pairs from different subtrees with sum of depths > k.
Algorithm
- 1For each node: collect depths from left and right subtrees. Count pairs (one from each) where d1+d2+2 > k (add 2 for edges to current node).
- 2Return merged depth list incremented by 1.
Common Pitfalls
- •Two-pointer on sorted depth lists to count valid pairs. Distance between nodes in different subtrees = d1+d2+2.
1530.cs
C#
// Approach: DFS returning depth-list of leaves; count pairs within distance using two-pointer on merged sorted lists.
// Time: O(n * distance²) Space: O(n)
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null)
{
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution
{
private int ans = 0;
public int CountPairs(TreeNode root, int distance)
{
dfs(root, distance);
return ans;
}
private int[] dfs(TreeNode root, int distance)
{
int[] d = new int[distance + 1];
if (root == null)
return d;
if (root.left == null && root.right == null)
{
d[0] = 1;
return d;
}
int[] dl = dfs(root.left, distance);
int[] dr = dfs(root.right, distance);
for (int i = 0; i < distance; ++i)
for (int j = 0; j < distance; ++j)
if (i + j + 2 <= distance)
ans += dl[i] * dr[j];
for (int i = 0; i < distance; ++i)
d[i + 1] = dl[i] + dr[i];
return d;
}
}Advertisement
Was this solution helpful?