问题
思路
深度优先即可。
代码
/**
* 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) {
std::vector<std::string> ret;
if(!root) return ret;
std::string s;
dfs(root, s, ret);
return ret;
}
private:
void dfs( TreeNode* root, std::string str, std::vector<std::string>& ret ){
if(!root) return;
if(!(root->left)&&!(root->right)){
str += int2Str(root->val);
ret.push_back(str);
}
else{
str += int2Str(root->val);
str += "->";
dfs(root->left, str, ret);
dfs(root->right, str, ret);
}
str.pop_back();
}
std::string int2Str(int val){
std::stringstream ss;
ss << val;
return ss.str();
}
};