【发布时间】:2020-10-18 05:11:47
【问题描述】:
我有一个保存播放器对象的 AVL 树。每个玩家都有一个名字和一个等级。树节点是根据玩家等级排序的。我首先遍历树的深度,并将每个节点附加到按等级排序的玩家列表中(按降序排列,因此从右到左遍历)。
我读到的所有内容都告诉我,AVL 树的复杂度为 O(log n),但是当我查看我的中序遍历函数时,我注意到它递归调用自身两次,我认为这会使它成为 O(2 ^n)。有没有更有效的方法来遍历我不知道的树?还是我的大 O 计算有误?
def traverseRightToLeft(node, array = []):
# Base case
if node is None:
return
# Recursively check if there are any right child nodes, append the current node data to the list then recursively check if there are any left child nodes
else:
traverseRightToLeft(node.right, array)
array.append(node.data)
traverseRightToLeft(node.left, array)
return array
【问题讨论】:
-
O(log n) 通常与单个项目树搜索有关。您正在遍历整棵树。
-
Usain Bolt 可以在 10 秒内跑完 100m,但那段时间他肯定跑不了马拉松。没有数据结构的时间复杂度,只有你可以用它做的每一件事的时间复杂度。
标签: python time-complexity big-o