通行证
- 积分
- 599
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2011-7-20
- 最后登录
- 1970-1-1
|
第二题, recursive O(n) solution:- #include <vector>
- #include <unordered_map>
- #include <unordered_set>
- #include <map>
- #include <set>
- #include <queue>
- #include <cmath>
- #include <algorithm>
- #include <numeric>
- #include <string>
- #include <list>
- #include <iostream>
- using namespace std;
- struct TreeNode
- {
- TreeNode(int i) : label(i) {}
- int label;
- vector<TreeNode *> childrens;
- };
- class Solution
- {
- public:
- TreeNode *root;
- Solution() {}
- int getParents()
- {
- int depth = 0;
- auto tmp = getParents(root, depth);
- return tmp->label;
- }
- TreeNode *getParents(TreeNode *root, int &depth)
- {
- if (root->childrens.empty())
- {
- depth = 1;
- return root;
- }
- vector<int> depths;
- vector<TreeNode *> roots;
- for (auto &v : root->childrens)
- {
- int depthtmp = 0;
- roots.push_back(getParents(v, depthtmp));
- depths.push_back(depthtmp);
- }
- int maxV = getMax(depths);
- depth = maxV + 1;
- auto count = countMax(depths, maxV);
- if (count.size() == 1)
- {
- return roots[count[0]];
- }
- else
- {
- return root;
- }
- }
- int getMax(vector<int> depths)
- {
- int ret = 0;
- for (auto &v : depths)
- {
- ret = max(ret, v);
- }
- return ret;
- }
- vector<int> countMax(vector<int> depths, int maxV)
- {
- vector<int> ret;
- for (int i = 0; i < depths.size(); i++)
- {
- if (depths[i] == maxV)
- ret.push_back(i);
- }
- return ret;
- }
- };
- int main()
- {
- TreeNode *root = new TreeNode(1);
- root->childrens.push_back(new TreeNode(2));
- root->childrens.push_back(new TreeNode(3));
- root->childrens.push_back(new TreeNode(4));
- root->childrens[0]->childrens.push_back(new TreeNode(5));
- // root->childrens[0]->childrens.push_back(new TreeNode(6));
- root->childrens[2]->childrens.push_back(new TreeNode(6));
- Solution sl;
- sl.root = root;
- cout << sl.getParents() << endl;
- return 0;
- }
复制代码 |
|