目录
题目描述:
示例1
解题思路:
代码实现:
题目描述:
给定一个二叉树,每个节点上站着一个人,节点数字表示父节点到该节点传递悄悄话需要花费的时间。
初始时,根节点所在位置的人有一个悄悄话想要传递给其他人,求二叉树所有节点上的人都接收到悄悄话花费的时间。
输入描述
给定二叉树
0 9 20 -1 -1 15 7 -1 -1 -1 -1 3 2
注:-1表示空节点
输出描述
返回所有节点都接收到悄悄话花费的时间38
示例1
输入输出示例仅供调试,后台判题数据一般不包含示例
输入
0 9 20 -1 -1 15 7 -1 -1 -1 -1 3 2
输出
38
解题思路:
递归遍历即可得到答案
代码实现:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;void talk(vector<vector<int>> &ps, vector<int> p, int idx, vector<int> &nds) {if (idx >= nds.size() || nds[idx] == -1) {ps.push_back(p);return;}p.push_back(nds[idx]);talk(ps, p, idx * 2 + 1, nds);talk(ps, p, idx * 2 + 2, nds);
}
int main()
{string st;getline(cin, st);stringstream ss(st);vector<int> nodes;int value;while (ss >> value) {nodes.push_back(value);}vector<vector<int>> ps;vector<int> path;talk(ps, path, 0, nodes);int maxValue = 0;for (auto pp : ps) {int sum = 0;for (auto p : pp) {sum += p;}if (sum > maxValue) maxValue = sum;}cout << maxValue << endl;return 0;
}