标签:leetcode
递归实现,深度遍历,记录每一条路径。
class Solution { public: int sumNumbers(TreeNode *root) { if(root==nullptr) return 0; vector<vector<int>> result; vector<int> path; traverse(root,result,path); int n=result.size(); int sum=0; for(int i=0;i<n;++i) { int tempsum=0; for(int j=0;j<result[i].size();++j) { tempsum=tempsum*10+result[i][j]; } sum=sum+tempsum; } return sum; } private: void traverse(TreeNode *root,vector<vector<int>> &result,vector<int> &path) { if(!root) { return; } if(root->left==nullptr&&root->right==nullptr) { path.push_back(root->val); result.push_back(path); path.pop_back(); return; } path.push_back(root->val); traverse(root->left,result,path); //path.pop_back(); traverse(root->right,result,path); path.pop_back(); } };
Leetcode_Sum Root to Leaf Numbers
标签:leetcode
原文地址:http://blog.csdn.net/yinqiaohua/article/details/43701881