-1

Given n distinct integers in the range 0, 1, ··· , n^5 − 1, design a worst-case linear-time algorithm to construct an AVL tree on these integers.

I think the idea is to shrink the problem basically meaning change the base from n^5 -1 to N and then inserting it into an AVL tree. But dont know how to do it though!

  • An AVL tree is just a self-balancing binary search tree. But, because you know all of the numbers ahead of time, you can add the numbers to the tree in [level order](https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search), which avoids the need for searching and re-balancing. You *do* have to compute the balance factors correctly. – user3386109 Aug 28 '19 at 16:28
  • 1
    Possible duplicate of [Balanced Binary Search Tree for numbers](https://stackoverflow.com/questions/16766159/balanced-binary-search-tree-for-numbers) – user3386109 Aug 28 '19 at 16:36

1 Answers1

2

The "n^5" gives it away: Sort the integers with radix sort, using n as the radix. This will take O(n) time (5 passes) and O(n) space. Then build a balanced binary tree.

See https://en.wikipedia.org/wiki/Radix_sort, and Building Red-Black Tree from sorted array in linear time

Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87