题目链接:https://leetcode-cn.com/problems/binary-tree-paths/
题目如下:
/**
* 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> result;
vector<int> path;
if(root==NULL) return result;
dfs(root,path,result);
return result;
}
void dfs(TreeNode* root,vector<int>& path,vector<string>& result){
path.push_back(root->val);
//终止条件:当找到叶子节点的时候,就将路径放入到result中
//即root->left==NULL&&root->right==NULL
if(root->left==NULL&&root->right==NULL){//遇到叶子节点,将路径放入result
string str_path="";
for(int e:path)
str_path+=to_string(e)+"->";
str_path[str_path.size()-1]=str_path[str_path.size()-2]=0;//去掉多余的->
result.push_back(str_path);
return ;
}
//单层逻辑(前序遍历——根左右)
if(root->left){
dfs(root->left,path,result);
path.pop_back();
}
if(root->right){
dfs(root->right,path,result);
path.pop_back();
}
}
};