/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int sum = 0; int sumRootToLeaf(TreeNode* root) { preOrder(root, 0); return sum; } void preOrder(TreeNode* node, int k) { if(node == nullptr) return ; k = (k << 1) + node->val; if(node->left == nullptr && node->right == nullptr) { sum += k; } preOrder(node->left, k); preOrder(node->right, k); } };