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"]
输出所有 从根节点到叶子节点的路径
/**
* 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<int> v ;
vector<string> s;
string invert( int n ) {//将数字转换为字符串
string s ;
if ( n < 0 ) n = - n ;
while ( n ) {
s += n%10 + '0';
n /= 10 ;
}
for ( int i = 0 ; i < s.size()/2 ; i ++) {
swap(s[i], s[s.size()-i-1]) ;
}
return s;
}
void pre(TreeNode* root) {
if ( !root ) return ;
if ( !root->left && !root->right ) { //leaf node
string t ;
for (int i = 0 ; i < v.size() ; i ++) {
if ( v[i] < 0 ) {
t += '-' ;
t += invert(v[i]) ;
}
else {
t += invert(v[i]) ;
}
t += "->" ;
}
if( root->val < 0 ) {
t += '-' ;
t += invert(root->val) ;
}
else
t += invert(root->val) ;
s.push_back(t) ;
return ;
}
v.push_back( root->val ) ;
pre( root->left ) ;
pre( root->right ) ;
v.pop_back() ;
}
vector<string> binaryTreePaths(TreeNode* root) {
v.clear() ;
s.clear() ;
pre( root ) ;
return s ;
}
};