Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1 / \ 2 3 \ 5
All root-to-leaf paths are:
["1->2->5", "1->3"]
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> ret;
if(!root) return ret;
vector<int> temp;
help(root,temp,ret);
return ret;
}
private:
void help(TreeNode* root,vector<int> temp,vector<string>& road)
{
temp.push_back(root->val);
if(!root->left&&!root->right)
{
string test=convert(temp);
road.push_back(test);
return;
}
else
{
if(root->left) help(root->left,temp,road);
if(root->right) help(root->right,temp,road);
}
}
string convert(const vector<int>& temp)
{
string ret=to_string(temp[0]);
for(int i=1;i<temp.size();i++)
{
ret=ret+"->"+to_string(temp[i]);
}
return ret;
}
};
第一次自己的代码accept然后超过86%,并且并没有什么太大的逻辑错误。
深度搜索有点类似于回朔算法。都是要在解空间中搜索满足条件的解。