Create Balanced Binary Search Tree from Sorted linked list

后端 未结 11 1750
囚心锁ツ
囚心锁ツ 2020-12-07 16:48

What\'s the best way to create a balanced binary search tree from a sorted singly linked list?

11条回答
  •  萌比男神i
    2020-12-07 17:27

    You can't do better than linear time, since you have to at least read all the elements of the list, so you might as well copy the list into an array (linear time) and then construct the tree efficiently in the usual way, i.e. if you had the list [9,12,18,23,24,51,84], then you'd start by making 23 the root, with children 12 and 51, then 9 and 18 become children of 12, and 24 and 84 become children of 51. Overall, should be O(n) if you do it right.

    The actual algorithm, for what it's worth, is "take the middle element of the list as the root, and recursively build BSTs for the sub-lists to the left and right of the middle element and attach them below the root".

提交回复
热议问题