257. Binary Tree Paths
做题历程:
- 本题做了不止2次了,本次大概耗时7分钟,独立解出
本题难度还是比较低的,就是单纯的用DFS就能解出,就不赘述了,直接上代码吧:
/**
* 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:
vector<string> binaryTreePaths(TreeNode* root) {
if (root != nullptr) {
dfs(root, "");
}
return res;
}
private:
vector<string> res;
void dfs(TreeNode* root, string s) {
if (s == "") {
s = s + to_string(root->val);
}
else {
s = s + "->" + to_string(root->val);
}
if (root->left == nullptr && root->right == nullptr) {
res.push_back(s);
return;
}
if (root->left != nullptr) {
dfs(root->left, s);
}
if (root->right != nullptr) {
dfs(root->right, s);
}
}
};