LeetCode 1530. 好叶子节点对的数量(思维)

题意:
给你二叉树的根节点 root 和一个整数 distance 。

如果二叉树中两个 叶 节点之间的 最短路径长度 小于或者等于 distance ,那它们就可以构成一组 好叶子节点对 。

返回树中 好叶子节点对的数量 。

数据范围:
tree 的节点数在 [1, 2^10] 范围内。
每个节点的值都在 [1, 100] 之间。
1 <= distance <= 10
解法:
考虑枚举lca=x,
然后计算有多少个满足条件的数对,其lca为x.

设x的左儿子为l,右儿子为r,
由于是二叉树,只需要处理出l子树中的叶子到l的距离,
以及r子树中的叶子到r的距离,然后l和r中的叶子互相配对即可.
code:
/**
 * 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) {}
 * };
 */
//const int maxm=1e5+5;
class Solution {
public:
    int dis;
    int ans;
    vector<int> dfs(TreeNode* root){
        if(!root)return vector<int>(dis,0);
        vector<int>l=dfs(root->left);
        vector<int>r=dfs(root->right);
        vector<int>now(dis,0);
        if(!root->left&&!root->right){
            now[0]=1;
        }
        for(int i=0;i<dis-1;i++){
            now[i+1]+=l[i]+r[i];
        }
        for(int i=1;i<dis;i++){
            l[i]+=l[i-1];
        }
        for(int i=0;i<dis;i++){//枚举右子树中的点
            int t=dis-2-i;//选择左子树中到l的距离<=t的点进行匹配.
            if(t>=0){
                ans+=l[t]*r[i];
            }
        }
        return now;
    }
    int countPairs(TreeNode* root, int distance) {
        dis=distance;
        ans=0;
        dfs(root);
        return ans;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值