❤ • 18天前
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
TreeNode *buildTree(const vector<int> &arr, int &id) {
if (id >= arr.size() || arr[id] == -1) {
id++;
return nullptr;
}
TreeNode *root = new TreeNode(arr[id]);
id++;
root->left = buildTree(arr, id);
root->right = buildTree(arr, id);
return root;
}
void dfs(TreeNode *root, int &sum, const vector<int> &arr, bool isLeft) {
if (!root)
return;
if (!root->left && !root->right && isLeft) {
sum += root->val;
return;
}
dfs(root->left, sum, arr, 1);
dfs(root->right, sum, arr, 0);
}
int main() {
vector<int> arr;
int t;
while (cin >> t) {
arr.push_back(t);
if (cin.get() == '\n')
break;
}
int id = 0;
TreeNode *root = buildTree(arr, id);
int sum = 0;
dfs(root, sum, arr, 0);
cout << sum << endl;
return 0;
}
评论:
请先登录,才能进行评论