Eat Study Love

먹고 공부하고 사랑하라

Coding_Practice

Number of Good Leaf Nodes Pairs[Tree,Depth-First Search,Binary Tree]

eatplaylove 2024. 9. 9. 10:26

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

 

Constraints:

  • The number of nodes in the tree is in the range [1, 210].
  • 1 <= Node.val <= 100
  • 1 <= distance <= 10

가다가 전혀 잡히지 않는다..

너무 빡센 문제

Solution을 대놓고 가져왔는데 그래도 빡세다.. 이게 뭐야 진짜 아오

 

1. C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    // returns distance to leaves in a sorted order
    vector<int> distanceToLeaves(TreeNode* cur, int& cnt, int dist){
        if(cur == nullptr) 
            return {};
        if(cur->left == nullptr && cur->right == nullptr){
            return {1};
        }

        vector<int> lefts = distanceToLeaves(cur->left, cnt, dist);
        vector<int> rights = distanceToLeaves(cur->right, cnt, dist);
        vector<int> res(lefts.size() + rights.size()); 

        int i = lefts.size() - 1, j = 0; 
        for(; i >= 0; i--){ // O(L + R)
            while(j < rights.size() && lefts[i] + rights[j] <= dist){
                j++;
            }
            cnt += j; 
        }
        // create sorted results 
        int l = 0, r = 0, idx = 0;
        while(l < lefts.size() && r < rights.size()){ // O(L + R)
            if(lefts[l] < rights[r]){
                res[idx++] = lefts[l++] + 1;
            }else{
                res[idx++] = rights[r++] + 1;
            }
        }
        while(l < lefts.size()){
            res[idx++] = lefts[l++] + 1;
        }
        while(r < rights.size()){
            res[idx++] = rights[r++] + 1;
        }
      
        return res; 
    }
    int countPairs(TreeNode* root, int distance) {
        int cnt = 0;
        distanceToLeaves(root, cnt, distance);
        return cnt;
    }
};

 

와따마 봐도 모르겄다.. GG

2. Python

class Solution:
    def countPairs(self, root: TreeNode, distance: int) -> int:
        self.map = {}
        self.leaves = []
        self.findLeaves(root, [], self.leaves, self.map)
        res = 0
        for i in range(len(self.leaves)):
            for j in range(i + 1, len(self.leaves)):
                list_i, list_j = self.map[self.leaves[i]], self.map[self.leaves[j]]
                for k in range(min(len(list_i), len(list_j))):
                    if list_i[k] != list_j[k]:
                        dist = len(list_i) - k + len(list_j) - k
                        if dist <= distance:
                            res += 1
                        break
        return res

    def findLeaves(self, node: TreeNode, trail: List[TreeNode], leaves: List[TreeNode], map: Dict[TreeNode, List[TreeNode]]):
        if not node:
            return
        tmp = trail[:]
        tmp.append(node)
        if not node.left and not node.right:
            map[node] = tmp
            leaves.append(node)
            return
        self.findLeaves(node.left, tmp, leaves, map)
        self.findLeaves(node.right, tmp, leaves, map)