# For a balanced binary search tree what is the worst case case time complexity for accessing all elements within a range of nodes?

I have this question which is asking for the worst case time complexity for a balanced binary search tree, assume the nodes are labeled as integers and we consider a range of [nodex, nodey], nodex<=nodey. And also given that the range has exactly k nodes, k can be at most n ie. total number of nodes. The question asks what is the worst case time complexity of accessing all the k nodes in given range. According to my knowledge of Time-Complexiy analysis It must be O(k*log(n)) since there are k elements and each element takes O(log(n)) time in worst case ( since the tree is balanced ) this seems very plausible, However the answer seems to be O(k + log(n)), what am I doing wrong?

2. Explore the left part of the subtree, and trim branches on the left that have a root $$\leqslant node_x$$;
3. Do the same thing on the right for roots $$\geqslant node_y$$
Each of those steps are done in $$O(\log n)$$ since the BST is balanced. Once you have constructed the tree, just do a tree traversal (in-order for example) of it. This last step is indeed done in $$O(k)$$.
• I see, Now I get it, I was confusing the range of nodes to be visited, to each one of the nodes, but I see why that's redundant all we would need is the end points of the range and since an inorder traversal can be done in O(k) the two have to be added, of course. It was so silly of me. Thanks for the answer. May 24, 2021 at 13:56