Skip to content

1530. Number of Good Leaf Nodes Pairs 👍

  • Time: $O(n)$
  • Space: $O(n)$
 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
class Solution {
 public:
  int countPairs(TreeNode* root, int distance) {
    int ans = 0;

    dfs(root, distance, ans);

    return ans;
  }

 private:
  vector<int> dfs(TreeNode* root, int distance, int& ans) {
    vector<int> d(distance + 1);  // {distance: the number of leaf nodes}
    if (root == nullptr)
      return d;
    if (root->left == nullptr && root->right == nullptr) {
      d[0] = 1;
      return d;
    }

    const vector<int> dl = dfs(root->left, distance, ans);
    const vector<int> dr = dfs(root->right, distance, ans);

    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;
  }
};
 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
class Solution {
  public int countPairs(TreeNode root, int distance) {
    dfs(root, distance);

    return ans;
  }

  private int ans = 0;

  private int[] dfs(TreeNode root, int distance) {
    int[] d = new int[distance + 1]; // {distance: the number of leaf nodes}
    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;
  }
}