思路:写两个binaryTreePaths函数,第一个使用递归方法构造题目要求的字符串,这个函数需要合理选择参数;第二个函数用来返回结果:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void binaryTreePaths(TreeNode* root, string s, vector<string> &result) {
if (!root->left && !root->right) {
result.push_back(s);
return;
}
if (root->left) binaryTreePaths(root->left, s + "->" + to_string(root->left->val), result);
if (root->right) binaryTreePaths(root->right, s + "->" + to_string(root->right->val), result);
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> vec;
if (root == NULL) return vec;
binaryTreePaths(root, to_string(root->val), vec);
return vec;
}
};