题目如下
思路与代码
二叉树,很熟悉,还是简单的二叉树,缪杀!
二叉树路径直接dfs深搜就可以了啊!
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<string> ans;
vector<string> binaryTreePaths(TreeNode* root) {
string path;
dfs(root,path);
return ans;
}
void dfs(TreeNode* root,string path){
if(!root) return;
if(!root->left&&!root->right){
ans.push_back(path+to_string(root->val));
return ;
}
if(root->left) dfs(root->left,path+to_string(root->val)+"->");
if(root->right) dfs(root->right,path+to_string(root->val)+"->");
}
};