基本可以算是树的层级遍历,很简单,一次就过了小数据和大数据;因为返回的是int,所以也不用考虑溢出的问题,直接逐层更新节点的数值,遇到叶子节点则加入到sum中,遍历结束之后返回sum即可。
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int sumNumbers(TreeNode *root) { 13 // Start typing your C/C++ solution below 14 // DO NOT write int main() function 15 if (root == NULL) 16 return 0; 17 int sum = 0; 18 deque<TreeNode*> layer; 19 layer.push_back(root); 20 while (!layer.empty()) { 21 TreeNode *current = layer.front(); 22 layer.pop_front(); 23 if (current->left == NULL && current->right == NULL) { 24 sum += current->val; 25 } 26 if (current->left != NULL) { 27 current->left->val += current->val * 10; 28 layer.push_back(current->left); 29 } 30 if (current->right != NULL) { 31 current->right->val += current->val * 10; 32 layer.push_back(current->right); 33 } 34 } 35 return sum; 36 } 37 };