题意:给定二叉树,找出所有根到叶子的路径
分析:dfs.
代码:
/**
* 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> binaryTreePaths(TreeNode* root) {
vector<string> ans;
//if(root==nullptr) return ans;
string curPath="";
dfs(ans,curPath,root);
return ans;
}
string getstring ( const int n ){
std::stringstream newstr;
newstr<<n;
return newstr.str();
}
void dfs(vector<string> &paths,string curPath,TreeNode* root){
if(root==nullptr) return;
if(root->left==nullptr&&root->right==nullptr){
paths.push_back(curPath+getstring(root->val));
return;
}
dfs(paths,curPath+getstring(root->val)+"->",root->left);
dfs(paths,curPath+getstring(root->val)+"->",root->right);
}
};
本文介绍了一种使用深度优先搜索(DFS)算法来查找给定二叉树中所有从根节点到叶子节点路径的方法。通过递归方式遍历树结构,并记录路径,最终收集所有路径并返回。
403

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



