思路:深度优先搜索
/**
* 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:
vector<string> binaryTreePaths(TreeNode* root) {
//保存结果
vector<string> res;
//进行DFS
dfs(root,"",res);
return res;
}
void dfs(TreeNode* root,string path,vector<string>& res){
//当前节点不为空
if(root!=nullptr){
//加上节点的值
path += to_string(root->val);
//如果当前节点为叶子节点则到头了加入结果并返回
if(root->left == nullptr && root->right == nullptr){
res.push_back(path);
return;
}
//当前节点不为空的话则需要向下搜索,左子树和右子树继续深度搜索
path += "->";
dfs(root->left,path,res);
dfs(root->right,path,res);
}
}
};