题目描述
思路分析
二叉树+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) {
dfs(root,to_string(root->val));
return ans;
}
void dfs(TreeNode* u,string cur){
if(!u->left&&!u->right){
ans.push_back(cur);
return;
}
if(u->left) dfs(u->left,cur+"->"+to_string(u->left->val));
if(u->right) dfs(u->right,cur+"->"+to_string(u->right->val));
}
};