这个参考了别人的,写的真好!
void binaryTreePaths(vector<string>& result, TreeNode* root,string t){
if(!root->left&&!root->right){
result.push_back(t);
return;
}
if(root->left) binaryTreePaths(result,root->left,t+"->"+to_string(root->left->val));
if(root->right) binaryTreePaths(result,root->right,t+"->"+to_string(root->right->val));
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> vec;
if(!root) return vec;
binaryTreePaths(vec,root,to_string(root->val));
return vec;
}
然后我这样修改了一下,时间变为原来的二分之一
vector<string> vec;
void binaryTreePaths(TreeNode* root,string t){
if(!root->left&&!root->right){
vec.push_back(t);
return;
}
if(root->left) binaryTreePaths(root->left,t+"->"+to_string(root->left->val));
if(root->right) binaryTreePaths(root->right,t+"->"+to_string(root->right->val));
}
vector<string> binaryTreePaths(TreeNode* root) {
if(!root) return vec;
binaryTreePaths(root,to_string(root->val));
return vec;
}