Concatenating/Merging/Joining two AVL trees

前端 未结 4 1930
有刺的猬
有刺的猬 2020-12-13 00:57

Assume that I have two AVL trees and that each element from the first tree is smaller then any element from the second tree. What is the most efficient way to concatenate th

4条回答
  •  死守一世寂寞
    2020-12-13 01:12

    One ultra simple solution (that works without any assumptions in the relations between the trees) is this:

    1. Do a merge sort of both trees into one merged array (concurrently iterate both trees).
    2. Build an AVL tree from the array - take the middle element to be the root, and apply recursively to left and right halves.

    Both steps are O(n). The major issue with it is that it takes O(n) extra space.

提交回复
热议问题