题目:
题解:
- 经典的dfs框架,大家直接看代码即可。
代码如下:
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
if(!root)return {};
vector<string> res;
helper(root,res,"");
return res;
}
void helper(TreeNode* root,vector<string>& res,string trace)
{
//1、递归边界
if(root==nullptr)return;
//2、递归表达式
trace+=to_string(root->val);
//3、寻找到一个可行解,即达到叶子节点,dfs结束
if(root->left==nullptr&&root->right==nullptr){
res.push_back(trace);
return;
}
//4、继续进行dfs
if(root->left)helper(root->left,res,trace+"->");
if(root->right)helper(root->right,res,trace+"->");
}
};