您的位置:首页 > 其它

[LeetCode]Sum Root to Leaf Numbers

2015-07-26 22:22 253 查看
解题思路:
深度遍历,记录所有leaf节点对应的number string,最后再把 string to int,进行计算。
/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode* root) {
vector<string> numbers;

search(root, "", numbers);
int ret = 0;
for (auto s : numbers){
ret += toInt(s);
}
return ret;
}

void search(TreeNode* root, string num, vector<string> &ret){
if (root == NULL) return;

string now = num + toString(root->val);
if (root->left == NULL && root->right == NULL){
ret.push_back(now);
}else{
search(root->left, now, ret);
search(root->right, now, ret);
}
return ;
}

string toString(int a){
stringstream ss;
ss << a;
string ret = ss.str();
ss.str("");

return ret;
}
int toInt(string s){
return atoi(s.c_str());
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: