Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
//
//
/// Approch 1: similar to 113
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<vector<int> > res;
vector<int> cur;
vector<string> result;
path(root, res, cur);
for (auto i : res) {
string s;
char notfirsr = 0;
for (auto j : i) {
if (notfirsr) {
s += "->";
s += to_string(j);
} else {
notfirsr = 1;
s += to_string(j);
}
}
result.push_back(s);
}
return result;
}
private:
void path(TreeNode* root, vector<vector<int> > &res, vector<int> &cur) {
if (nullptr == root) return;
cur.push_back(root->val);
if (nullptr == root->left && nullptr == root->right) {
res.push_back(cur);
}
path(root->left, res, cur);
path(root->right, res, cur);
cur.pop_back();
}
};
//
//
/// Approch 2:
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string>res;
if (root == nullptr)return res;
if (root->left == nullptr && root->right == nullptr) {
res.push_back(to_string(root->val));
return res;
}
vector<string>leftS = binaryTreePaths(root->left);
for (int i = 0; i < leftS.size(); i++)
res.push_back(to_string(root->val) + "->" + leftS[i]);
vector<string>rightS = binaryTreePaths(root->right);
for (int i = 0; i < rightS.size(); i++)
res.push_back(to_string(root->val) + "->" + rightS[i]);
return res;
}
};