简单题,递归就ok
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int sum; void thesum(TreeNode* root, int n){ if(root -> left == NULL && root -> right == NULL){ sum = sum + n * 10 + root -> val; return ; } if(root -> left != NULL) thesum(root -> left, n * 10 + root -> val); if(root -> right != NULL) thesum(root -> right, n * 10 + root -> val); } int sumNumbers(TreeNode* root) { if(root == NULL) return 0; sum = 0; thesum(root, 0); return sum; }};新闻热点
疑难解答