美团笔试第3题


美图第三题,用map来访问子树,并合并,map大小就是不重复字母总数。

#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <map>
using namespace std;

struct Node
{
    char val;
    Node * left;
    Node * right;
    Node(){val = 0;left=nullptr;right=nullptr;}
    Node(int x){val = x;left=nullptr;right=nullptr;}
};

// 全局定义
unordered_map<int, Node*> umap; // 序号+指针
unordered_map<Node*, int> rmap; // 指针+子树的结果

Node* build(vector<int> data, string str){
    Node* head = new(Node);
    head->val = str[0];
    umap[0] = head;
    rmap[head] = 0;
    for (int i = 0; i < data.size(); i++)
    {
        int index = i+1;
        // 找到头结点
        Node* cur = umap[data[i]-1];
        // 建立一个节点
        Node* nn = new(Node);
        nn->val = str[index];
        if(cur->left == nullptr){
            cur->left = nn;
            umap[index] = cur->left;
            rmap[cur->left] = 0;
        }
        else{
            cur->right = nn;
            umap[index] = cur->right;
            rmap[cur->right] = 0;
        }
    }
    return head;
    
}


map<char, Node*> readNode(Node* head){
    map<char, Node*> smap;  // 树下的map用来求数量
    if(head == nullptr)
        return smap;
    map<char, Node*> rl = readNode(head->left);
    map<char, Node*> rr = readNode(head->right);
    smap[head->val] = head;
    smap.insert(rl.begin(), rl.end());
    smap.insert(rr.begin(), rr.end());
    rmap[head] = smap.size();
}

int main(){
    int a;
    cin>>a;
    int b = a;
    vector<int> sdata;
    while (--a)
    {
        int x;
        cin>>x;
        sdata.push_back(x);
    }
    string str;
    cin>>str;

    // 构建二叉树
    Node* head = build(sdata, str);

    // 遍历节点
    auto rs = readNode(head);

    //  输出
    for (int i = 0; i < umap.size(); i++)
    {
        Node* cur = umap[i];
        if (i<umap.size()-1)
            cout<<rmap[cur]<<" ";
        else
            cout<<rmap[cur];
    }

    return 0;

}

/* 样例
6
1 2 2 1 4
ABCCAD

*/


#美团笔试#
全部评论
这题里面保证了是二叉树吗
1 回复 分享
发布于 2022-09-03 13:47 上海
hi~同学,秋招遇“寒气”,牛客送温暖啦!23届秋招笔面经有奖征集中,参与就得牛客会员7天免费体验,最高赢300元京东卡!戳我去看>>>https://www.nowcoder.com/link/zhengjipinglun
点赞 回复 分享
发布于 2022-09-04 08:59 北京
有java题解吗
点赞 回复 分享
发布于 2022-09-03 21:58 陕西
请问你这个代码A了多少啊?
点赞 回复 分享
发布于 2022-09-03 14:39 香港

相关推荐

09-22 22:22
中山大学 Java
双尔:赌对了,不用经历秋招的炼狱真的太好了,羡慕了
点赞 评论 收藏
分享
用微笑面对困难:这里面最强的是驾驶证了,可以入职美团大厂,然后直接开启黄马褂人生
点赞 评论 收藏
分享
看新闻上说,印度媒体都在密集发申请攻略,咨询量直接涨了30%印度、韩国、新加坡的申请意愿特别突出,感觉要成科技人才的新选择了~我的offer还没有呢!
ysb:哥们就不明白了,自己的人才都留不住,然后找外国,咋滴给外国人才高福利朝九晚五不加班是吗,然后我们大学生996,加班,无offer,摆地摊,送外卖是吗,有点意思,很英明
我的秋招日记
点赞 评论 收藏
分享
评论
点赞
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务