Replace suboptimal O(n) time/space inorder vector approach with O(k + h) time, O(h) space recursive solution that short-circuits once the kth smallest is found#113
Open
ultrakapy wants to merge 1 commit intoByteByteGoHq:mainfrom
Conversation
…(h) space recursive solution that short-circuits once the kth smallest is found
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The previous implementation collected all node values into a vector via a full inorder traversal before indexing into it, resulting in O(n) time and O(n) space regardless of where the kth smallest element sits in the tree.
The new implementation passes
kby reference as a countdown and short-circuits as soon as it reaches zero. When the kth node is found, thereturnprevents any further right subtree traversal in that frame. For ancestors that were waiting on a left call, theif (k == 0) returnguard intercepts them before they descend right, ensuring no unnecessary nodes are visited after the answer is found.This brings time complexity down to O(k + h) and space complexity down to O(h), where h is the height of the tree. In the worst case (skewed tree) h = n, but for balanced trees this is a significant improvement over the previous approach.