257. Binary Tree Paths
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3
思路:采用先序遍历的方法,每次先把字符串加起来(传下去,因此递归函数还需要一个当前字符串),判断如果没有孩子了,则将字符串处理成要求格式,加到集合里;如果有左,则递归遍历左;如果有右,则递归遍历右。
/**
* 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) {
vector<string>re;
if (!root)
return re;
Paths(root, re, "");
return re;
}
void Paths(TreeNode* root, vector<string>&re, string s)
{
//s用来记录上一次
s = s+"->"+to_string(root->val);//每次先用空格隔开
if (!root->left&&!root->right)
//去掉最开始的箭头
re.push_back(s.substr(2));
//去除两端空格,并把中间的空格 用箭头替代
//类似先序遍历,现在处理左
if (root->left)
Paths(root->left, re, s);
if (root->right)
Paths(root->right, re, s);
}
};