LeetCode/solutions/257. Binary Tree Paths.md

34 lines
1.2 KiB
Markdown
Raw Normal View History

2018-11-12 16:22:23 +00:00
# [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;
}
};
```