257. 二叉树的所有路径
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:void paths(vector<string> &res, string path, TreeNode * root){path += to_string(root->val); // 先插入节点if(root->left == nullptr && root->right == nullptr) {res.push_back(path);return;}path += "->";if(root->left) paths(res,path, root->left);if(root->right) paths(res, path, root->right);}vector<string> binaryTreePaths(TreeNode* root) {vector<string> res;if(root == nullptr) return res; // 这里已经进行了判断,所以传入的不会是空节点paths(res, "", root);return res;}
};