题解:
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
1
/ \
2 3
\
5
输出: ["1->2->5", "1->3"]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-paths
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解:
/**
* 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;
string a;
vector<string> binaryTreePaths(TreeNode* root) {
if(root==NULL) return ans;
string path;
dfs(root,path);
return ans;
}
void dfs(TreeNode* root,string path){
if(root==NULL) return;
if(root->left==NULL&&root->right==NULL){
path += to_string(root->val);
cout<<path<<endl;
ans.push_back(path);
return;
}
path += to_string(root->val) + "->";
dfs(root->left,path);
dfs(root->right,path);
}
};
思路:
我就是直接dfs,然后这里有一个技巧,就是撤销你的选择!
我这里是直接前序遍历,然后传入直接是字符串,而不是地址(不会涉及对path的修改),这样在遍历结束后path就会减去我加上的东西!