通行证
- 积分
- 502
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2021-11-9
- 最后登录
- 1970-1-1
|
没找到原题,自己写了一个版本大家参考一下
#include <iostream>
#include <unordered_map>
#include <queue>
using namespace std;
class NTree {
public:
unordered_map<char, NTree*> children;
char key;
int val;
NTree(char key, int val): key(key), val(val) {}
~NTree() {
for (auto& child: children) {
if (child.second) {
delete child.second;
}
}
}
void print() {
queue<NTree*> q;
q.push(this);
while (q.size()) {
int size = q.size();
for(; size > 0; --size) {
auto cur = q.front();
q.pop();
cout << cur->key << ":" << cur->val << ",";
for (auto pair: cur->children) {
q.push(pair.second);
}
} cout << endl;
}
}
};
class Solution {
public:
NTree* merge(NTree* t1, NTree* t2) {
if (!t1 || !t2) {
return nullptr;
}
if (t1->key != t2->key) {
return nullptr;
}
// 只有在t1,t2非空并且key相同时才能合并
NTree* newTree = new NTree(t1->key, t1->val + t2->val);
// 遍历t1->children,公共的节点merge,单独节点深度拷贝
for (auto pair1: t1->children) {
char key = pair1.first;
NTree* child1 = pair1.second;
if (t2->children.count(key)) {
newTree->children[key] = merge(child1, t2->children[key]);
} else {
newTree->children[key] = deepCopy(child1);
}
}
// 遍历t2->children,公共的节点已经merge,跳过,单独节点深度拷贝
for (auto pair2: t2->children) {
char key = pair2.first;
NTree* child2 = pair2.second;
if (!t1->children.count(key)) {
newTree->children[key] = deepCopy(child2);
}
}
return newTree;
}
private:
NTree* deepCopy(NTree* t) {
if (!t) {
return nullptr;
}
NTree* newTree = new NTree(t->key, t->val);
for (auto& child: t->children) {
newTree->children[child.first] = deepCopy(child.second);
}
return newTree;
}
};
int main()
{
std::cout<<"Built Tree1" << endl;
NTree* t1 = new NTree('A', 3);
t1->children['F'] = new NTree('F', 3);
t1->children['B'] = new NTree('B', 1);
t1->children['R'] = new NTree('R', 6);
t1->print();
std::cout<<"Built Tree2" << endl;
NTree* t2 = new NTree('A', 8);
t2->children['F'] = new NTree('F', 7);
t2->children['R'] = new NTree('R', 3);
t2->print();
Solution s;
std::cout<<"Merge Tree1 and Tree2" << endl;
NTree* newTree = s.merge(t1, t2);
newTree->print();
return 0;
}
// print
Built Tree1
A:3,
R:6,B:1,F:3,
F:15,C:18,
Built Tree2
A:8,
R:3,F:7,
Merge Tree1 and Tree2
A:11,
F:10,B:1,R:9,
C:18,F:15, |
|