# [257. Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/description/) # 思路 递归算法,用一个curr_path记录当前的path,每当遇到叶子节点时就将curr_path push到一个字符串数组里。 # C++ ``` C++ class Solution { private: vectorres; string curr_path; void find_leaf(TreeNode* root){ if(root == NULL) return; if(!curr_path.empty()) curr_path += "->"; // 不是第一个数,应该先加上“->” curr_path += (to_string(root -> val)); if(root -> right == NULL && root -> left == NULL) res.push_back(curr_path); find_leaf(root -> left); find_leaf(root -> right); // 将当前节点从curr_path中删掉,注意可能是负数所以不能用“-”作为箭头的标志 while(!curr_path.empty() && curr_path[curr_path.size()-1] != '>'){ // 删除最后一个字符直到curr_path空了或者遇到箭头的标志">" curr_path.erase(curr_path.end() - 1); } if(!curr_path.empty()) curr_path.erase(curr_path.size() - 2, 2); // 删除末尾的"->" } public: vector binaryTreePaths(TreeNode* root) { find_leaf(root); return res; } }; ```