原题地址(简单)
方法1—深度优先搜索
思路
此题是比较简单的关于二叉树的题目,运用深搜即可解决。
需要注意的是结点的值有可能>10,也有可能是0,也有可能是负数。
代码
class Solution {public:vector<string> ans;void dfs(string path, TreeNode* root){if(!root->left && !root->right){ans.push_back(path);return;}if(root->left) dfs(path+"->"+to_string(root->left->val), root->left);if(root->right) dfs(path+"->"+to_string(root->right->val), root->right);}vector<string> binaryTreePaths(TreeNode* root) {if(!root) return {};string path = to_string(root->val);dfs(path, root);return ans;}};
时空复杂度
摘自官方题解

