[LeetCode]Sum Root to Leaf Numbers
2015-07-26 22:22
253 查看
解题思路:
深度遍历,记录所有leaf节点对应的number string,最后再把 string to int,进行计算。
深度遍历,记录所有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()); } };
相关文章推荐
- OpenGL教程翻译 第十三课 相机空间
- aaaaaaaaaaaaa
- 面试准备之数据库部分
- <复习>指针结构体内存分配
- CDOJ 485 UESTC 485 Game (八数码变形,映射,逆cantor展开)
- Oracle忘记密码
- UGUI下拉列表控件
- C++primer——阅读笔记(非面向对象)
- arm指令集----ldr 和 mov的区别
- 快速Android开发系列通信篇之EventBus
- 如何买玫瑰?
- WebPlotDigitizer Ploty 图形数据获取利器!!!
- 栈与队列
- [leedcode 142] Linked List Cycle II
- Android(java)学习笔记129:Tab标签的使用
- 最长公共子序列
- 控件与组件
- android intent调用隐式调用系统
- DICOM:dcm4che工具包如何压缩dcm文件探讨(前篇)
- jQuery的.bind()、.live()和.delegate()之间区别