개발 공부/TIL(Today I Learned)

99클럽 코테 스터디 33일차 TIL Number of Good Leaf Nodes Pairs

애해 2024. 8. 23. 20:48
728x90

# 오늘의 학습 키워드 

깊이/너비 우선 탐색(DFS/BFS)

 

# 오늘의 문제 

https://leetcode.com/problems/number-of-good-leaf-nodes-pairs/description/

You are 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:

 

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:

 

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].

 

# 나의 풀이방식 

 

/**
 * Definition for a binary tree node.
 * public 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;
 *     }
 * }
 */
class Solution {
    public int countPairs(TreeNode root, int distance) {
    
    	// 주어진 distance가 2보다 작으면 유효한 쌍이 존재할 수 없으므로 메서드는 0을 반환
        if (distance < 2) {
            return 0;
        }
        
        return pairs(root, distance)[0];
    }

    private int[] pairs(TreeNode node, int distance) {
        int[] r = new int[distance];
        if (node == null) {
            return r;
        }
        if (node.left == null && node.right == null) {
            r[1] = 1;
            return r;
        }
        int[] rl = pairs(node.left, distance);
        int[] rr = pairs(node.right, distance);
        for (int i = 2; i < distance; i++) {
            r[i] = rl[i - 1] + rr[i - 1];
        }
        int pairs = rl[0] + rr[0];
        for (int dist = 2; dist <= distance; dist++) {
            for (int leftToNodeDist = 1; leftToNodeDist < dist; leftToNodeDist++) {
                pairs += rl[leftToNodeDist] * rr[dist - leftToNodeDist];
            }
        }
        r[0] = pairs;
        return r;
    }


}

 

반응형