257. 二叉树的所有路径
题目
传送门:https://leetcode.cn/problems/binary-tree-paths/
算法设计:深度优先搜索
遍历二叉树的同时,所有路径都会记录下来。
- 不要一个一个添加到列表里,先用字符串存储,遇到叶子节点统一添加
class Solution {
public:
vector<string> ans;
void dfs(TreeNode* node, string path) {
if(node->left == NULL && node->right == NULL)
ans.push_back(path + to_string(node->val));
if(node->left)
dfs(node->left, path + to_string(node->val) + "->");
if(node->right)
dfs(node->right, path + to_string(node->val) + "->");
}
vector<string> binaryTreePaths(TreeNode* root) {
dfs(root, "");
return ans;
}
};