1.二叉树的所有路径
思路一:DFS
/**
* 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:
void construct(TreeNode* p,string path,vector<string>& paths)
{//字符串不需要引用,因为是一条
if(p==nullptr) return;
path+=to_string(p->val);
if(p->left==nullptr&&p->right==nullptr)
{
paths.push_back(path);
}
else
{
path+="->";
construct(p->left,path,paths);
construct(p->right,path,paths);
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> paths;
construct(root,"",paths);
return paths;
}
};
京公网安备 11010502036488号