Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/gjh13/article/details/90742767
Problem-solving ideas:
Using a depth-first search (DFS), depth-first search termination condition is: the current root node is a leaf node, namely:! Root-> left && root-> right is true, then found a path!.
/**
* 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) return {};
vector<string> res;
dfs(res, root, to_string(root->val));
return res;
}
void dfs(vector<string>& res, TreeNode* root, string tmp){
if(!root->left && !root->right){
res.push_back(tmp);
return;
}
if(root->left)
dfs(res, root->left, tmp + "->" + to_string(root->left->val));
if(root->right)
dfs(res, root->right, tmp + "->" + to_string(root->right->val));
}
};