Given a BST with n nodes, the algorithm should create a linked list that contains a decreasing order sorted array. The algorithm should have a worst case time complexity O(n). The signature of the function should be toList(T, L), where T is the root of the tree and L is a linked list. The only operation that allowed to use in the linked list is InsertFront.

My attempt:

toList(T , L){
   if (T == null) return
   toList(T.right , L)
   toList(T.left , L)

What do you think about that?

Any suggestions will be great!

Thanks a lot!

  • 2
    $\begingroup$ Looks correct for me $\endgroup$
    – nir shahar
    May 15, 2021 at 18:32
  • $\begingroup$ just make sure that the insersions to the list won't take linear time (since then, the algorithm will take $O(n^2)$ time; $O(n)$ per node, and $n$ nodes) $\endgroup$
    – nir shahar
    May 15, 2021 at 18:34
  • $\begingroup$ @nirshahar,InsertFront should be constant time (unless perversely implemented, that is). $\endgroup$
    – vonbrand
    May 15, 2021 at 19:03
  • $\begingroup$ We discourage "please check whether my answer is correct" questions, as only "yes/no" answers are possible, which won't help you or future visitors. See here and here. Can you edit your post to ask about a specific conceptual issue you're uncertain about? As a rule of thumb, a good conceptual question should be useful even to someone who isn't looking at the problem you happen to be working on. If you just need someone to check your work, you might seek out a friend, classmate, or teacher. $\endgroup$
    – D.W.
    May 16, 2021 at 1:19
  • $\begingroup$ We are a question-and-answer site, so we require you to articulate a specific, answerable question. "What do you think about that?" is too open-ended and not a good fit; see our help center. $\endgroup$
    – D.W.
    May 16, 2021 at 1:20

1 Answer 1


The idea seems alright, just a tiny bit of comments:

  • InsertFront(T) should instead be InsertFront(T.root) (or you will get a linked list of trees).
  • As is, your function takes two arguments: a tree T and a linked list L, and add the in-order of T in front of L, and returns nothing. If you want a function that returns the in-order, you could add:
   L <- empty linked list
   toList(T, L)
   return L

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.