【发布时间】:2021-12-02 09:28:34
【问题描述】:
链表
链表的插入时间复杂度对于实际操作来说是 O(1),但是需要 O(n) 时间才能遍历到正确的位置。大多数在线资源将链表的平均插入时间列为 O(1):
https://stackoverflow.com/a/17410009/10426919
https://www.bigocheatsheet.com/
https://www.geeksforgeeks.org/time-complexities-of-different-data-structures/
英国夏令时
二叉搜索树的插入需要遍历节点,耗时 O(log n)。
问题
Am I mistaken to believe that insertion in a BST also takes O(1) time for the actual operation?
类似于链表的节点,在 BST 中插入节点只会将当前节点的指针指向被插入节点,而被插入节点将指向当前节点的子节点。
If my thinking is correct, why do most online resources list the average insert time for a BST to be O(log n), as opposed to O(1) like for a linked list?
似乎对于链表,实际插入时间被列为插入时间复杂度,但对于BST,遍历时间被列为插入时间复杂度。
【问题讨论】:
-
如果不保持 BST 平衡,那么找到正确的插入点需要 O(log n),添加节点需要 O(1)。但是如果你确实保持树平衡,找到正确的插入点需要 O(log n),添加节点需要 O(1),重新平衡树可能需要 O(log n)。如果您在插入后不重新平衡,那么最坏情况的搜索时间可能会降低到 O(n)。在这种情况下,BST 与链表完全相同。所以关键是当人们谈论 BST 时,他们通常会假设这棵树是一个平衡 BST。
标签: algorithm data-structures time-complexity complexity-theory space-complexity