描述
代码
/**
* 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:
void binaryTreePaths(TreeNode* root,vector<string> & paths,string path)
{
//c++11
// int2string
path+= to_string(root->val);
//是叶子节点
if(root->left==nullptr&&root->right==nullptr)
{
paths.push_back(path);
return;
}
//深度优先搜索
if(root->left)//有左叶子节点
{
binaryTreePaths(root->left,paths, path+"->");
}
if(root->right)//有右叶子节点
{
binaryTreePaths(root->right,paths, path+"->");
}
}
vector<string> binaryTreePaths(TreeNode* root)
{
vector<string> res;
if(root==nullptr)
{
return res;
}
binaryTreePaths(root,res,"");
return res;
}
};