- 将您的树
T1 和 T2 转换为排序列表 L1 和 L2
- 将
L1 和L2 合并到一个排序列表L
- 再次将
L 转换为树T。
IIRC 所有这些操作都是 O(N),所以完全合并也是 O(N)。
如果您的 AVL 树表示允许有效地迭代它们(例如,使用反向指针、延续、惰性求值等),那么您应该也可以在没有中间列表的情况下完成它。
更新:由于您的编程语言似乎是 C/C++,您可能会暂时滥用您的 AVL 节点结构作为链表中的节点,然后再将它们再次用于输出树。
更新 2:@hwlau:这是 O(N),我使用我自己在 Prolog 中的 AVL 实现检查了它,可从 avl.pl 和这个测试程序 avl_test.pl 检查数字合并大小为 1、2、4、8、16、...的 AVL 树时的操作次数。
这是输出:
timing avl_merge, size: 128
% 1,790 inferences, 0.000 CPU in 0.001 seconds (0% CPU, Infinite Lips)
timing avl_merge, size: 256
% 3,591 inferences, 0.010 CPU in 0.002 seconds (430% CPU, 359100 Lips)
timing avl_merge, size: 512
% 7,176 inferences, 0.030 CPU in 0.028 seconds (107% CPU, 239200 Lips)
...
timing avl_merge, size: 32000
% 451,839 inferences, 0.490 CPU in 0.499 seconds (98% CPU, 922120 Lips)
timing avl_merge, size: 64000
% 903,682 inferences, 0.900 CPU in 0.964 seconds (93% CPU, 1004091 Lips)
timing avl_merge, size: 128000
% 1,807,363 inferences, 2.420 CPU in 2.559 seconds (95% CPU, 746844 Lips)
很明显,推理/操作的数量与合并树的大小成正比,因此算法的复杂度为 O(N)。