Day133 | 灵神 | 回溯算法 | 子集型 二叉树的所有路径

257.二叉树的所有路径

257. 二叉树的所有路径 - 力扣(LeetCode)

思路:

这道题思路比较简单,直接写就行

完整代码:

cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
vector<string> res;
void dfs(TreeNode *t,string path)
{
if(t==nullptr)
return ;
path += to_string(t->val);
if(t->left==nullptr&&t->right==nullptr)
{
res.push_back(path);
return ;
}
path += "->";
dfs(t->left,path);
dfs(t->right,path);
}
vector<string> binaryTreePaths(TreeNode* root) {
string path;
dfs(root,path);
return res;
}
};