本题考察对二叉树的理解,题解:计算从根节点到某叶子节点的最大和路径
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int num;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : num(x), left(nullptr), right(nullptr) {}
};
//根据arr层序遍历构造完全二叉树
TreeNode* binaryTree(vector<int> arr, int index) {
if (index >= arr.size()) {
return nullptr;
}
TreeNode* node = new TreeNode(arr[index]);
node->left = binaryTree(arr, 2 * index + 1);
node->right = binaryTree(arr, 2 * index + 2);
return node;
}
// dfs函数,接受两个参数:当前节点和当前路径的和
int dfs(TreeNode* node, int& maxSum) {
if (node == nullptr || node->num == -1) {
return 0;
}
int leftSum = dfs(node->left, maxSum);
int rightSum = dfs(node->right, maxSum);
int currentSum = node->num + max(leftSum, rightSum);//目前的最大值
maxSum = max(maxSum, currentSum); // 更新最大路径和
return currentSum; // 返回当前路径的和
}
int main() {
int num;
vector<int> arr;
while (cin >> num) {
arr.push_back(num);
}
TreeNode *root = binaryTree(arr, 0);
int maxSum = 0; // 用于存储最大路径和的变量
dfs(root, maxSum); // 调用dfs并传入最大路径和的引用
cout << maxSum << endl;
return 0;
}