题目描述:
https://leetcode-cn.com/problems/binary-tree-paths/
代码:递归
class Solution {
private:
vector<string> ans;
public:
vector<string> binaryTreePaths(TreeNode* root) {
if(!root)
return ans;
DFS(root, to_string(root->val));
return ans;
}
void DFS(TreeNode * root, string str)
{
if(!root->right && !root->left)
{
ans.push_back(str);
return;
}
if(root->left != NULL)
DFS(root->left, str+"->"+to_string(root->left->val));
if(root->right != NULL)
DFS(root->right, str+"->"+to_string(root->right->val));
}
};