LeetCode No.257 Binary Tree Paths
来源:互联网 发布:java jvm调优 编辑:程序博客网 时间:2024/05/22 09:48
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"]
====================================================================================
题目链接:https://leetcode.com/problems/binary-tree-paths/
题目大意:求出二叉树中所有从头结点到叶子节点的路径。
思路:递归,对二叉树进行深搜,到达叶子节点的时候就记录下来。
注意点:将整数转成字符串的时候注意
附上代码:
/** * 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: vector<string> binaryTreePaths(TreeNode* root) { vector <string> ans ; if ( root == NULL ) return ans ; string s = "" ; s += intToString ( root -> val ) ; createPaths ( root , s , ans ) ; return ans ; }private : void createPaths ( TreeNode* root , string s , vector <string>& ans ) { if ( root -> left == NULL && root -> right == NULL ) { ans.push_back ( s ) ; return ; } s += "->" ; if ( root -> left ) { string str = s + intToString ( root -> left -> val ) ; createPaths ( root -> left , str , ans ) ; } if ( root -> right ) { string str = s + intToString ( root -> right -> val ) ; createPaths ( root -> right , str , ans ) ; } } string intToString ( int n ) { if ( n == 0 ) return "0" ; if ( n < 0 ) return "-" + intToString ( -n ) ; string ans = "" ; while ( n ) { ans = char ( n % 10 + '0' ) + ans ; n /= 10 ; } return ans ; }};
0 0
- LeetCode No.257 Binary Tree Paths
- 【LeetCode】No.257 Binary Tree Paths
- leetcode 257: Binary Tree Paths
- leetCode #257 Binary Tree Paths
- LeetCode(257)Binary Tree Paths
- [leetcode 257]Binary Tree Paths
- leetcode[257] Binary Tree Paths
- LeetCode 257: Binary Tree Paths
- leetcode 257 : Binary Tree Paths
- 【LEETCODE】257-Binary Tree Paths
- [leetcode 257] Binary Tree Paths
- LeetCode 257 Binary Tree Paths
- LeetCode 257:Binary Tree Paths
- LeetCode 257:Binary Tree Paths
- leetcode 257:Binary Tree Paths
- leetcode-257-Binary Tree Paths
- LeetCode 257Binary Tree Paths
- LeetCode 257 Binary Tree Paths
- revit二次开发获取墙的几何信息
- Binder基本概念流程学习
- Intellij IDEA调试功能使用总结(step over / step into / force step into/step out等)
- RTMPdump 使用说明
- revit二次开发里的复制粘贴
- LeetCode No.257 Binary Tree Paths
- revit二次开发常用语句 结合二次开发书更好用
- python中写入csv,excel显示、pandas读取csv文件的编码问题
- Android UI测试-Espresso环境搭建及测试(by 星空武哥)
- 构建fabric
- @OneToMany、@ManyToOne以及@ManyToMany讲解
- skew数
- 【转载】Java多线程编程2--同步锁定--synchronized同步方法、脏读、锁重入
- asp.net core 学习资料整理