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 ;
}
};