129 Sum Root to Leaf Numbers
1
/ \
2 3void dfs_root_sum(TreeNode *cur_node, string &cur_string, vector<int> &root_leaf_paths)
{
if (cur_node) {
cur_string += to_string(cur_node->value);
// is leaf node
if (!cur_node->left && !cur_node->right) {
root_leaf_paths.push_back(stoi(cur_string));
}
dfs_root_sum(cur_node->left, cur_string, root_leaf_paths);
dfs_root_sum(cur_node->right, cur_string, root_leaf_paths);
cur_string.pop_back();
}
}
int sumNumbers(TreeNode *root)
{
vector<int> root_leaf_paths;
string cur_string;
dfs_root_sum(root, cur_string, root_leaf_paths);
int total_sum = 0;
for (int i : root_leaf_paths) {
total_sum += i;
}
return total_sum;
}Last updated