leetcode:257 Binary Tree Paths-每日编程第四十五题
2015-12-29 14:48
471 查看
Binary Tree Paths
Total
Accepted: 27476 Total
Submissions: 108456 Difficulty: Easy
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
All root-to-leaf paths are:
Total
Accepted: 27476 Total
Submissions: 108456 Difficulty: Easy
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1 / \ 2 3 \ 5
All root-to-leaf paths are:
["1->2->5", "1->3"]
<span style="font-size:14px;">/** * 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: void int2string(string& str,int val){ if(val==0){ return; } char ch=(val%10)+'0'; int2string(str,val/10); str+=ch; return; } string int2string(int val){ string str; if(val<0){ str+="-"; val*=-1; } int2string(str,val); return str; } void binaryTreePaths(TreeNode* root,vector<string>& vec,string str){ string ch=int2string(root->val); str+="->"; str+=ch; if(root->left==NULL&&root->right==NULL){ vec.push_back(str); return; } if(root->left!=NULL){ binaryTreePaths(root->left,vec,str); } if(root->right!=NULL){ binaryTreePaths(root->right,vec,str); } } vector<string> binaryTreePaths(TreeNode* root) { vector<string> vec; if(root==NULL){ return vec; } string ch=int2string(root->val); string str; str+=ch; if(root->left==NULL&&root->right==NULL){ vec.push_back(str); return vec; } if(root->left!=NULL){ binaryTreePaths(root->left,vec,str); } if(root->right!=NULL){ binaryTreePaths(root->right,vec,str); } return vec; } };</span>
相关文章推荐
- java -------SimpleDateFormat之后为何多了一年
- Spark访问HBase的Eclipse代码实现
- PYTHON设计模式,创建型之简单工厂模式
- Qt单实例程序(防止程序多开)
- 并发编程之五--ThreadLocal
- qt 写文件
- Java项目中读取properties文件
- LeetCode 3Sum 求和 java
- C++自定义时间格式
- 保存文件为UTF8格式XML file(Writing UTF-8 files in C++)
- PHP中一个好用的函数parse_url
- Java设计模式_行为型_迭代器模式_如何打印一张菜单
- C#与MATLAB混合编程
- c语言位域
- PAT-有理数加法(基础编程题)
- 使用Eclipse进行远程调试 外加 ant 直接打包到服务器
- Eclipse/myeclipse快捷键大全
- java数据存储
- java 反射: 当Timestamp类型的属性值为null时,设置默认值
- 《C++Primer 5e》学习笔记(3):表达式