代码随想录:二叉树的所有路径
代码随想录:二叉树的所有路径
如果传入的&的话,需要在调用后进行回溯,不如直接传绝对值
/**
* 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:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
vector<int> path;
tra(root, path, res);
return res;
}
void tra(TreeNode* node, vector<int> path, vector<string>& res) {
path.push_back(node->val);
if (node->left == NULL && node->right == NULL) {
string r = "";
for (int i = 0; i < path.size(); i++) {
if (i == 0) {
r += to_string(path[i]);
} else {
r += "->";
r += to_string(path[i]);
}
}
res.push_back(r);
}
if (node->left)
tra(node->left, path, res);
if (node->right)
tra(node->right, path, res);
}
};

浙公网安备 33010602011771号