problem:
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
tip:
二叉树返回所有根到叶结点的路径,树型题目,多用递归。
solution:
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
if(!root) return {};
if(!root->left && !root->right) return {to_string(root->val)};
vector<string> res;
for(string st : binaryTreePaths(root->left))
{
res.push_back(to_string(root->val)+"->"+st);//???
}
for(string st : binaryTreePaths(root->right))
{
res.push_back(to_string(root->val)+"->"+st);
}
return res;
}
};
2.当前路径结束后,将它存储。
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
if(!root) return {};
vector<string> res;
if(root) helper(root,"",res);
return res;
}
//这里的out代表当前结点之前的路径,当完成一条路径遍历后,将其存储在vector中
void helper(TreeNode* root,string out,vector<string>& res)//这里的引用很重要,没有的话程序是错误的.因为不加引用只是对形参做了修改,实参没有变化。
{
if(!root->left && !root->right) res.push_back(out+to_string(root->val));
if(root->left) helper(root->left,out+to_string(root->val)+"->",res);
if(root->right) helper(root->right,out+to_string(root->val)+"->",res)
}
};