层次遍历即可
如果该节点有左儿子,那么更新左儿子的val
如果该节点有右儿子,那么更新右儿子的val
如果该节点是叶子节点,那么res加上该节点的val
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @return int整型
*/
int sumNumbers(TreeNode* root) {
// write code here
int res=0;
if(root==NULL) return res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int size=q.size();
while(size--){
TreeNode* father=q.front();
q.pop();
if(father->left==NULL&&father->right==NULL) res+=father->val;
if(father->left) father->left->val+=10*father->val,q.push(father->left);
if(father->right) father->right->val+=10*father->val,q.push(father->right);
}
}
return res;
}
};