题目描述,链接https://leetcode-cn.com/problems/binary-tree-paths/
解题代码
/**
* 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> binaryTreePaths(TreeNode* root) {
vector<vector<int>> paths;
vector<string> spaths;
if(root==NULL){
return spaths;
}
vector<int> temp;
temp.push_back(root->val);
findPath(paths, temp, root);
int size = paths.size();
for(int i=0; i<size; i++){
string str=to_string(paths[i][0]);
int len = paths[i].size();
for(int j=1; j<len; j++){
str += "->";
str += to_string(paths[i][j]);
}
spaths.push_back(str);
}
return spaths;
}
void findPath(vector<vector<int>>& paths, vector<int> temp, TreeNode* root){
if(root->left==NULL && root->right==NULL){
paths.push_back(temp);
return;
}
if(root->left!=NULL){
temp.push_back(root->left->val);
findPath(paths, temp, root->left);
temp.pop_back();
}
if(root->right!=NULL){
temp.push_back(root->right->val);
findPath(paths, temp, root->right);
temp.pop_back();
}
return;
}
};
运行结果