题解 | #二叉树根节点到叶子节点的所有路径和#
二叉树根节点到叶子节点的所有路径和
https://www.nowcoder.com/practice/185a87cd29eb42049132aed873273e83
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ #include <vector> class Solution { public: /** * * @param root TreeNode类 * @return int整型 */ vector<vector<int>> v_v; vector<int> v; void dfs(TreeNode* root) { if(!root) { return; } v.emplace_back(root->val); if(!root->left && !root->right) { v_v.emplace_back(v); return; } if(root->left) { dfs(root->left); v.pop_back(); } if(root->right) { dfs(root->right); v.pop_back(); } return; } int sumNumbers(TreeNode* root) { // write code here dfs(root); int ans=0; for(auto temp_v_v:v_v) { int temp = 0; for(auto temp_v:temp_v_v) { temp = temp*10 + temp_v; } ans += temp; } return ans; } };
C++题库 文章被收录于专栏
非淡泊无以明志,非宁静无以致远