Created
January 15, 2018 02:59
-
-
Save jianminchen/6c9700fea710263c5a42188bffc60525 to your computer and use it in GitHub Desktop.
Find inorder successor in binary search tree
This file contains 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
/* | |
Assumptions: | |
all keys in the tree are nonnegative | |
strictly less than (no equal to) | |
if no smaller key return -1 | |
2 | |
/ \ num = 3 -> 2 | |
1 5 num = 7 -> 5 | |
num = 2 -> 1 | |
2 num = 1 -> -1 | |
Overview: | |
recursive approach | |
base case: comparing against a node that has no children | |
if key is smaller than num | |
return num | |
else | |
return -1 | |
standard binary search tree traversal for nodes with children | |
worst case: O(N) expected case: O(logN) | |
size complexity: recrusive so depth of the recursive tree <- potentially improve with iterative | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment