# 257. Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

``````   1
/   \
2     3
\
5
``````

All root-to-leaf paths are:

``````["1->2->5", "1->3"]
``````

``````class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if (root) helper(root, "", res);
return res;
}
void helper(TreeNode* node, string out, vector<string>& res) {
if (!node->left && !node->right) res.push_back(out + to_string(node->val));
if (node->left) helper(node->left, out + to_string(node->val) + "->", res);
if (node->right) helper(node->right, out + to_string(node->val) + "->", res);
}
};
``````

``````class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
if (!root) return {};
if (!root->left && !root->right) return {to_string(root->val)};
vector<string> left = binaryTreePaths(root->left);
vector<string> right = binaryTreePaths(root->right);
left.insert(left.end(), right.begin(), right.end());
for (auto &a : left) {
a = to_string(root->val) + "->" + a;
}
return left;
}
};
``````

``````class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
if (!root) return {};
if (!root->left && !root->right) return {to_string(root->val)};
vector<string> res;
for (string str : binaryTreePaths(root->left)) {
res.push_back(to_string(root->val) + "->" + str);
}
for (string str : binaryTreePaths(root->right)) {
res.push_back(to_string(root->val) + "->" + str);
}
return res;
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/257

Path Sum II

https://leetcode.com/problems/binary-tree-paths/

https://leetcode.com/problems/binary-tree-paths/discuss/68258/Accepted-Java-simple-solution-in-8-lines

https://leetcode.com/problems/binary-tree-paths/discuss/68282/Clean-Java-solution-(Accepted)-without-any-helper-recursive-function

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation