Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created January 15, 2018 02:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/6c9700fea710263c5a42188bffc60525 to your computer and use it in GitHub Desktop.
Save jianminchen/6c9700fea710263c5a42188bffc60525 to your computer and use it in GitHub Desktop.
Find inorder successor in binary search tree
/*
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