Problem:Given a binary tree, return all root-to-leaf paths.
Solution:每个结点记录从root至其的path,当结点无左右孩子时,将path传入进vector。
这里需要注意的是,recordPath函数中,path记录着root至结点的path,不可改变,不能加&(reference),而pathResult需要添加新的path,所以要加&。
void recordPath(TreeNode* tn,vector<int> path,vector< vector<int> >& pathResult)
class Solution {
void recordPath(TreeNode* tn,vector<int> path,vector< vector<int> >& pathResult){
path.push_back(tn->val);
if(!tn->left&&!tn->right)
pathResult.push_back(path);
if(tn->left)
recordPath(tn->left,path,pathResult);
if(tn->right)
recordPath(tn->right,path,pathResult);
return;
}
void convert(ve,vector< vector<int> > path)ctor<string>& result{
int rowSize=path.size();
for(int i=0;i<rowSize;i++){
string tmp;
tmp=to_string(path[i][0]);
for(int j=1;j<path[i].size();j++){
tmp+="->";
tmp+=to_string(path[i][j]);
}
result.push_back(tmp);
}
return;
}
public:
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
*/
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
vector< vector<int> > pathResult;
vector<int> tmp;
if(!root)
return result;
recordPath(root,tmp,pathResult);
convert(result,pathResult);
return result;
}
};