解题思路
深度优先搜索,若结点为叶子结点,则结果res加上cur * 10 加上叶子结点的值,若不为叶子结点,则深度搜索该结点的左右结点,若遇到的结点为空的话则直接return
代码
class Solution {
public:void dfs(TreeNode *root,int &res,int cur){if(root == NULL)return;if(root->left == NULL && root->right == NULL){res += cur * 10 + root->val;}dfs(root->left,res,cur * 10 + root->val);dfs(root->right,res,cur * 10 + root->val);}int sumNumbers(TreeNode *root) {if(root == NULL)return 0;int res = 0;dfs(root,res,0);return res;}
};