257. 二叉树的所有路径
题目描述
给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
解题思路
class Solution {
void f(TreeNode* root, string path, vector<string> &res) {
path += to_string(root->val);
if (!root->left && !root->right) {
res.push_back(path);
return;
}
if(root->left)f(root->left,path+"->",res);
if(root->right)f(root->right,path+"->",res);
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
string path;
if (!root) return res;
f(root, path, res);
return res;
}
};