LeetCode 129. Sum Root to Leaf Numbers
原题链接
中等
作者:
JasonSun
,
2020-08-16 06:11:39
,
所有人可见
,
阅读 402
Tree Fold
class Solution {
public:
int sumNumbers(TreeNode* root) {
std::function<int(TreeNode*, int)> fold = [&](TreeNode* node, int init) {
if (node == nullptr) {
return 0 ;
}
else if (node->left == nullptr and node->right == nullptr) {
return (10 * init + node->val);
}
else {
return fold(node->left, 10 * init + node->val) + fold(node->right, 10 * init + node->val);
}
};
return fold(root, 0);
}
};