mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
34 lines
1.2 KiB
Markdown
34 lines
1.2 KiB
Markdown
# [257. Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/description/)
|
||
# 思路
|
||
递归算法,用一个curr_path记录当前的path,每当遇到叶子节点时就将curr_path push到一个字符串数组里。
|
||
|
||
# C++
|
||
``` C++
|
||
class Solution {
|
||
private:
|
||
vector<string>res;
|
||
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<string> binaryTreePaths(TreeNode* root) {
|
||
find_leaf(root);
|
||
return res;
|
||
}
|
||
};
|
||
```
|