思路
1、深度优先,先序遍历
2、和剑指offer34(和为某一值的二叉树路径)思路一样
代码
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ class Solution { public: /** * * @param root TreeNode类 * @return int整型 */ int sum = 0; vector<vector<int>> res; // 前序遍历 void helper(TreeNode* root, vector<int>& path){ if(root==nullptr) { return; } path.push_back(root->val); if(root->left==nullptr && root->right==nullptr){ res.push_back(path); } helper(root->left, path); helper(root->right, path); path.pop_back(); } int compute_res(vector<vector<int>> res){ int sum = 0; for(const auto& path:res){ int tmp = 0; for(const auto& ele:path){ tmp*=10; tmp += ele; } sum+=tmp; } return sum; } int sumNumbers(TreeNode* root) { // write code here vector<int> path; helper(root, path); auto ans = compute_res(res); return ans; } };