/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ class Solution { public: /** * * @param root TreeNode类 * @return int整型 */ int preOrder(TreeNode* root, int sum) { // sum 存储路径总和 if(!root) return 0; sum = sum * 10 + root->val; // 当路径中节点不为空就将节点加入进sum if(!root->left && !root->right) // 当当前节点没有子树时,返回当前这一路径的路径和 return sum; return preOrder(root->left, sum) + preOrder(root->right, sum); // 返回左子树路径和 + 右子树路径和 } int sumNumbers(TreeNode* root) { // write code here int res = 0; res = preOrder(root, 0); return res; } };