主页有其他数据结构内容(持续更新中)
难度:Easy
代码:
```cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void dfs(TreeNode* root, string path, vector<string>& res) {
if (root == nullptr) {
return;
}
path += to_string(root->val);
if (root->left == nullptr && root->right == nullptr) {
// 碰到了叶子节点
res.emplace_back(path);
return;
}
dfs(root->left, path + "->", res);
dfs(root->right, path + "->", res);
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
dfs(root, "", res);
return res;
}
};