/**
* 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 getPath(TreeNode* root, vector<int>& path, vector<string>& result) {
if (root) path.push_back(root->val);
// 叶子节点
if (!root->left && !root->right) {
string subRes;
for (int i = 0; i < path.size()-1; i++) {
subRes += to_string(path[i]);
subRes += "->";
}
subRes += to_string(path[path.size()-1]);
result.push_back(subRes);
}
// 左子树
if (root->left) {
getPath(root->left, path, result);
path.pop_back();
}
// 右子树
if (root->right) {
getPath(root->right, path, result);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<int> path;
vector<string> result;
if (!root) return result;
getPath(root, path, result);
return result;
}
};
总结
- 前序遍历将路径记录
- 回溯