题目来源LeetCode
题目描述
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”]
这道题也是一道DFS的题,其实就是在于string类型的转换,用到了to_string函数,具体代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
void dfs(TreeNode*root, vector<string> & result, string p){
if(root->left == NULL && root->right == NULL){
result.push_back(p);
return;
}
if(root->left != NULL){
string s;
s = p+"->" + to_string(root->left->val);
dfs(root->left, result, s);
}
if(root->right != NULL){
string s;
s = p + "->" + to_string(root->right->val);
dfs(root->right, result, s);
}
}
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
string s;
vector<string>paths;
if(root == NULL) return paths;
s = to_string(root->val);
dfs(root,paths,s);
return paths;
}
};