Number of Good Leaf Nodes Pairs | LeetCode Problems And Solution

This post explains the LeetCode problem Number of Good Leaf Nodes Pairs step by step: the problem statement, input and output format, constraints, a sample test case and a working solution in Java and Python that you can study and run.

Number of Good Leaf Nodes Pairs | LeetCode Problems And Solution | CodingHumans

Difficulty:Medium

Given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance.

Return the number of good leaf node pairs in the tree.

Example 1

Number of Good Leaf Nodes Pairs | LeetCode Problems And Solution | CodingHumans

Input: root = [1,2,3,null,4], distance = 3
Output: 1

Explanation: The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair.

Example 2

Number of Good Leaf Nodes Pairs | LeetCode Problems And Solution | CodingHumans

Input: root = [1,2,3,4,5,6,7], distance = 3
Output: 2

Explanation: The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4.

Example 3

Input: root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3
Output: 1
Explanation: The only good pair is [2,5].

Example 4

Input: root = [100], distance = 1
Output: 0

Constraints

The number of nodes in the tree is in the range [1, 2^10].
Each node's value is between [1, 100].
1 <= distance <= 10

Number of Good Leaf Nodes Pairs Solution in Java

class Solution {
  int ans = 0;

     public int countPairs(TreeNode root, int distance) {
      ans = 0;
         dfs(root, distance);
         return ans;
     }

     List<Integer> dfs(TreeNode root, int distance)
     {
      if(root == null)return new ArrayList<Integer>();
      if(root.left == null && root.right == null){
       List<Integer> ret = new ArrayList<>();
       ret.add(0);
       return ret;
      }

      List<Integer> L = dfs(root.left, distance);
      List<Integer> R = dfs(root.right, distance);
      for(int x : L){
       for(int y : R){
        if(x + y + 2 <= distance){
         ans++;
        }
       }
      }
      List<Integer> ret = new ArrayList<>();
      for(int x : L)ret.add(x+1);
      for(int x : R)ret.add(x+1);
      return ret;
     }
 }

Number of Good Leaf Nodes Pairs Solution in Python

class Solution(object):
    def countPairs(self, root, distance):
        graph = collections.defaultdict(list)
        M = {}
        nodes = []
        leaves = set()
        self.t = 0
        def dfs(node):
            if node:
                M[node] = ans = self.t
                self.t += 1

                v1 = dfs(node.left)
                v2 = dfs(node.right)
                if v1 is not None:
                    graph[ans].append(v1)
                    graph[v1].append(ans)
                if v2 is not None:
                    graph[ans].append(v2)
                    graph[v2].append(ans)
                if v1 is v2 is None:
                    leaves.add(ans)
                return ans

        dfs(root)
        Minv = [0] * len(M)
        for node in M:
            i = M[node]
            Minv[i] = node

        #print("!", leaves, graph)
        ans = 0
        for i in leaves:
            rooty = i
            queue = [[i, 0]]
            seen = {i}
            for node, d in queue:
                if d > distance: break
                if node in leaves and node != rooty:
                    #print("!", node, d)
                    ans += 1
                for nei in graph[node]:
                    if nei not in seen:
                        seen.add(nei)
                        queue.append([nei, d + 1])

        return ans // 2

If you have any doubts regarding this problem or need the solution in other programming languages then leave a comment down below .

Tip: try to solve the problem yourself before reading the solution. Use the code as a reference to check your approach, and make sure you understand why it works.

More LeetCode solutions All coding problems MCQ practice

Comments

Answered 0/0Correct 0