/**
* 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:
string makePath(const vector<int>& path) {
string path_str = to_string(path[0]);
for(int i = 1; i < path.size(); i++) {
path_str = path_str + "->" + to_string(path[i]);
}
return path_str;
}
void getPath(TreeNode* node, vector<int>& path, vector<string>& result) {
path.push_back(node->val);
if(node->left == nullptr && node->right == nullptr) {
result.push_back(makePath(path));
return;
}
if(node->left) {
getPath(node->left, path, result);
path.pop_back();
}
if(node->right) {
getPath(node->right, path, result);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
vector<int> path;
getPath(root, path, result);
return result;
}
};
精简版
class Solution {
private:
void traversal(TreeNode* cur, string path, vector<string>& result) {
path += to_string(cur->val); // 中
if (cur->left == NULL && cur->right == NULL) {
result.push_back(path);
return;
}
if (cur->left) traversal(cur->left, path + "->", result); // 左
if (cur->right) traversal(cur->right, path + "->", result); // 右
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
string path;
if (root == NULL) return result;
traversal(root, path, result);
return result;
}
};