计算 AVL 树中节点数的算法

Algorithm to count number of nodes in an AVL tree

Assume the following notation/operations on AVL trees. An empty AVL tree is denoted E. A non-empty AVL tree T has three attributes:

• The key T.key is the root node’s key.

• The left child T.left is T’s left subtree, which is an AVL tree (possibly E).

• The right child T.right is T’s right subtree, which is an AVL tree (possibly E).

我正在尝试编写一个算法(伪代码会做)Count(T, lo, hi) 计算和 returns AVL 树中具有根 T 的节点数,其中键值在 lo ≤ key ≤ hi 范围内。我希望它具有时间复杂度 O(n),其中 n 是 AVL 树 T 中的节点数。我的一个想法是递归,但这似乎没有所需的复杂性。有什么想法吗?

您可以添加一个全局变量,如计数器,用 Pre-order 迭代树,成本为 (n+e) 并为每个节点加 1。

你也可以添加一个计数器,在数据结构中添加一个新节点时,可以加1,如果删除一个节点,则可以减1