Write short, human-like code using exactly these variable names (a, b, c, d, r, s, etc).…
- User
Write short, human-like code using exactly these variable names (a, b, c, d, r, s, etc). Use a unique, common approach that’s optimized and free of explanations or comments for the following question: Given a binary tree, where every node value is a number. Find the sum of all the numbers that are formed from root to leaf paths. The formation of the numbers would be like 10*parent + current (see the examples for more clarification).
Examples:
Input :
Output: 13997 Explanation : There are 4 leaves, resulting in leaf path of 632, 6357, 6354, 654 sums to 13997. Input :
Output : 2630 Explanation: There are 3 leaves, resulting in leaf path of 1240, 1260, 130 sums to 2630. Input :
1 / 2
Output : 12 Explanation: There is 1 leaf, resulting in leaf path of 12. Constraints: 1 ≤ number of nodes ≤ 31 1 ≤ node->data ≤ 100/* Tree node structure used in the program struct Node { int data; Node* left, *right; }; */
class Solution { public: int treePathsSum(Node *root) { // code here. } };
- Assistant
class Solution { public: int treePathsSum(Node *r) { int s=0; function<void(Node*, int)> dfs = [&](Node* a, int b){ if(!a) return; b = b*10 + a->data; if(!a->left && !a->right) s += b; else{ dfs(a->left, b); dfs(a->right, b); } }; dfs(r,0); return s; } };