1530. Number of Good Leaf Nodes Pairs

29 篇文章 0 订阅
11 篇文章 0 订阅

1530. Number of Good Leaf Nodes Pairs

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

Example 4:

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

Example 5:

Input: root = [1,1,1], distance = 2
Output: 1

 

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

解题思路:dfs 每个父结点负责统计以它为根节点情况下,左子树和右子树的叶子结点满足条件的配对数

class Solution {
public:
    int res;
    int countPairs(TreeNode* root, int distance) {
        dfs(root, distance);
        
        return res;
    }
    
    vector<int> dfs(TreeNode* root, int distance)
    {
        if(root == NULL)
            return {};
        
        if(root->left == NULL && root->right == NULL)
            return{1};
        
        auto left = dfs(root->left, distance);
        auto right = dfs(root->right, distance);
        for(auto l:left)
            for(auto r:right)
            {
                if(l + r <= distance)
                    res++;
            }
        
        vector<int> tmp;
        for(auto l:left)
        {
            if(l + 1 <= distance)
            {
                tmp.push_back(l+1);    
            }            
        }
        
        for(auto r:right)
        {
            if(r + 1 <= distance)
            {
                tmp.push_back(r+1);    
            }            
        }
        
        return tmp;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值