#include <string>
#include <iostream>
#include <map>
#include <functional>
#include <algorithm>
#include <vector>
#include <cstdio>
using namespace std;
int n,m;
vector<string> nameMap;//index to name
vector<vector<string>> tree;
map<string, int> nodeIndex;//name to index
void dfs(vector<vector<string>> tree, int root,string mark)
{
if (root == 0) cout << nameMap[0] << endl;
if (tree[root].size() > 0)
{
for (int i = 0; i < tree[root].size(); ++i)
{
if (i < tree[root].size() - 1)
{
cout<<mark << "|--" << nameMap[nodeIndex[tree[root][i]]] << endl;
dfs(tree, nodeIndex[tree[root][i]], mark+"| ");
}
else
{
cout<<mark << "`--" << nameMap[nodeIndex[tree[root][i]]] << endl;
dfs(tree, nodeIndex[tree[root][i]], mark + " ");
}
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
cin >> n;
tree = vector<vector<string>>(n, vector<string>());
for (int i = 0; i < n; ++i)
{
int parent;
string tmpStr;
cin >> tmpStr;
nameMap.push_back(tmpStr);
cin >> parent;
while (nodeIndex.find(tmpStr) != nodeIndex.end())
{
tmpStr += "*";
}
nodeIndex[tmpStr] = i;
if (parent > -1)
{
tree[parent].push_back(tmpStr);
}
}
for (int i = 0; i < n; ++i)
{
if (tree[i].size() > 0)
{
sort(tree[i].begin(), tree[i].end());
}
}
dfs(tree, 0,"");
return 0;
}
分享一下自己AC的答案,同是没有offer的菜鸟,大家一起加油!
#Java工程师##C++工程师#