这个参考了别人的,写的真好!
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;
}
本文介绍了一种优化后的二叉树所有根到叶子节点路径的查找算法。通过减少不必要的字符串拼接操作,该优化使得算法运行时间缩短至原始版本的一半。文中提供了详细的代码实现及对比。

468

被折叠的 条评论
为什么被折叠?



