LeetCode 129. 求根节点到叶节点数字之和
思路:
dfs,用sum去维护每棵树的和。
代码:
/**
* 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 {
public:
int res = 0;
int sumNumbers(TreeNode* root) {
if(!root) return 0;
dfs(root,0);
return res;
}
void dfs(TreeNode* root,int sum){
sum = sum * 10 + root->val;
//只有是根节点才不需要乘以倍数 否则都需要乘倍数
if(!root->left && !root->right) res+=sum;
if(root->left) dfs(root->left,sum);
if(root->right) dfs(root->right,sum);
}
};
评论区