javascript - PreOrder Traversal Iterativ vs Recursive Time Complexity
问题描述
我正在为我的 Web 应用程序使用树。例如,创建一个个人资料网站,每个个人资料可以有 0..n 个朋友。另外,我想在最好的时间寻找朋友。为此,我使用了二叉搜索树和广度优先搜索 (BFS)。
我测量了我的两个函数在递归和迭代列表中搜索朋友的时间,令我惊讶的是递归函数更快。我认为迭代函数比迭代更快,我只在迭代函数中使用了一次 while 循环,时间复杂度为 O(n)。有人可以解释这里出了什么问题以及为什么递归函数更快:
时间递归:1.3000000035390258
preorderRec(root){
if(root === null) {
return;
}
console.log(root.data);
if(root.left) {
this.preorderRec(root.left);
}
if(root.right) {
this.preorderRec(root.right);
}
return root;
}
时间迭代:0.997000001117587
preOrderIterativ(root) {
if(root === null) {
return;
}
const stack = [root];
const stack2 = [];
while(stack.length) {
//const node = stack.pop();
const node = stack.pop();
stack2.push(node)
if(node.left) {
stack.push(node.left)
}
if(node.right) {
stack.push(node.right)
}
}
return stack2;
} }
解决方案:问题出在while循环中的console.log。我使用 repl.it 作为编辑器,在我删除 console.log 后,性能得到了提升
解决方案
在迭代解决方案中,您正在使用另一个数据结构 ( array
)。最重要的是,您不断地执行插入push
和删除pop
操作。这些操作中的每一个都是O(n)
时间复杂度。使用您正在使用的递归解决方案,call stack
这就是javascript
运行的方式。我不知道大O。
推荐阅读
- flutter - 如何通过文档 ID 获取 Firestore 集合快照
- python - 为什么python不通过迭代替换列表的新值?
- java - Spring Batch - 最大工人数?
- google-my-business-api - 通知“创建帖子需要主题类型”
- c++ - C ++继承:具有基类类型的虚函数中派生类类型的参数
- python - 在 Tkinter 首次运行问题上调整画布大小
- angular - 无法在 Angular 中进行确认删除工作
- c# - 使用 asp net core SignalR 应用程序进行水平缩放
- java - Spring Boot、六边形架构和分布式事务
- python - 如何保持 ssh 连接打开并在 python 中执行多个请求和输出