leetcode链接:https://leetcode.cn/problems/sum-of-root-to-leaf-binary-numbers/description/
代码:
class Solution {
public:
int sum (TreeNode* root , int num = 0) {
if (root == nullptr) {
return 0;
}
int cur = num + root->val;
if (root->left == nullptr && root->right == nullptr) {
return cur;
}
return sum(root->left , cur << 1) + sum(root->right , cur << 1);
}
int sumRootToLeaf(TreeNode* root) {
return sum(root);
}
};
递归展开图: