/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<string>ans;//存放路径;
void dfs(string path,TreeNode*root)
{
if(!root)return;
if(path.size()) path+="->";
path+=to_string(root->val);
if(!root->left&&!root->right) ans.push_back(path);
dfs(path,root->left);
dfs(path,root->right);
}
vector<string> binaryTreePaths(TreeNode* root) {
string path;//建立路径;
dfs(path,root);
return ans;
}
};
leetcode 257. 二叉树的所有路径
最新推荐文章于 2025-03-22 00:45:00 发布
本文介绍了一种使用深度优先搜索(DFS)遍历二叉树并获取所有从根节点到叶子节点路径的方法。通过递归的方式记录路径,并将完整的路径字符串存入结果集合中。
1125

被折叠的 条评论
为什么被折叠?



