Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 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 {
- private:int sum;
- private:void cal_sum(int leafnum,TreeNode* root)
- {
- leafnum = leafnum*10 + root->val;
- if(root->left==nullptr && root->right==nullptr)
- {
- sum+=leafnum;
- }
- else
- {
- if(root->left!=nullptr)
- {
- cal_sum(leafnum,root->left);
- }
- if(root->right!=nullptr)
- {
- cal_sum(leafnum,root->right);
- }
- }
- }
- public:int sumNumbers(TreeNode* root) {
- sum=0;
- cal_sum(0,root);
- return sum;
- }
- };
Advertisement