给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明:
示例:
输入:
1
/ 2 3
5
输出: ["1->2->5", "1->3"]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
此题使用深度优先遍历算法,每次遍历到一个节点就把该节点的值存入string中,然后判断是否为叶
节点:如果为叶子节点就需要把该条路路径添加进vector中。
本题需要注意vector中存储的是string,对自定义函数的传参有一个清晰的认识:
输出结果只需要一个包含所有路径string的vector,所以vector采用引用传参
每次递归过程中,当前结点产生的string都会进行变化(除非是叶结点),每次都要生成一个传入string的副本,因此采用值传递。这样就意味着每个函数中的path均不相同。
另外,考虑到string,我们需要使用to_string函数对root->val进行数据类型的转换
代码如下:
/**
* 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:
//因为每次迭代的string其实不一样,所以使用值传递
//但是每次迭代的vector只需要一个最终结果,所以使用引用传递
void findPath(TreeNode* root, string path, vector<string> &res){
if(root==NULL)
return ;
if(path!="")
path.append("->");
path.append(to_string(root->val));
if(root->left==NULL && root->right==NULL)
res.push_back(path);
findPath(root->left, path, res);
findPath(root->right, path, res);
}
vector<string> binaryTreePaths(TreeNode* root) {
string path;
vector<string> res;
findPath(root, path, res);
return res;
}
};
原文:https://www.cnblogs.com/buryinshadow/p/13603902.html