1 /*
 2  * @Author: your name
 3  * @Date: 2020-11-12 08:47:08
 4  * @LastEditTime: 2020-11-12 09:11:21
 5  * @LastEditors: Please set LastEditors
 6  * @Description: In User Settings Edit
 7  * @FilePath: \git\leetcode\257.二叉树的所有路径.cpp
 8  */
 9 /*
10  * @lc app=leetcode.cn id=257 lang=cpp
11  *
12  * [257] 二叉树的所有路径
13  */
14 
15 // @lc code=start
16 /**
17  * Definition for a binary tree node.
18  * struct TreeNode {
19  *     int val;
20  *     TreeNode *left;
21  *     TreeNode *right;
22  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
23  * };
24  */
25 class Solution {
26 public:
27 /*在深度优先搜索遍历二叉树时,我们需要考虑当前的节点以及它的孩子节点。
28 
29 如果当前节点不是叶子节点,则在当前的路径末尾添加该节点,并继续递归遍历该节点的每一个孩子节点。
30 如果当前节点是叶子节点,则在当前路径末尾添加该节点后我们就得到了一条从根节点到叶子节点的路径,将该路径加入到答案即可。
31 
32 */
33     vector<string> binaryTreePaths(TreeNode* root) {
34         if(!root) return {};
35         vector<string> res;
36         helper(root, res, "");
37         return res;
38     }
39 
40     void helper(TreeNode* root,vector<string>& res,string trace){
41        //1、递归边界
42         if(root==nullptr)
43             return;
44          //2、递归表达式
45         trace += to_string(root->val);
46         //3、寻找到一个可行解,即达到叶子节点,dfs结束
47         if(root->left==nullptr&&root->right==nullptr){
48             res.push_back(trace);
49             return;
50         }
51         //4、继续进行dfs
52         if(root->left)
53             helper(root->left, res, trace + "->");
54         if(root->right)
55             helper(root->right, res, trace + "->");
56     }
57 };
58 // @lc code=end