leetcode257-二叉树的所有路径
257. 二叉树的所有路径
泪目,自己写出的递归遍历.
/**
* 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> res;
void Tracking(TreeNode* root,string sss)
{
if(root==nullptr) return;
sss += ("->" + to_string(root->val));
Tracking(root->left,sss);
Tracking(root->right,sss);
if(!root->left&&!root->right) res.push_back(sss);
}
vector<string> binaryTreePaths(TreeNode* root) {
if(!root->left&&!root->right) return {to_string(root->val)};
Tracking(root->left,to_string(root->val));
Tracking(root->right,to_string(root->val));
return res;
}
};