Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jianminchen/7b0c94a34923dc9e2b44c41171c20aa4 to your computer and use it in GitHub Desktop.
Save jianminchen/7b0c94a34923dc9e2b44c41171c20aa4 to your computer and use it in GitHub Desktop.
binary search tree in order successor mock interview - Jan. 20, 2018
// Given the node with value 14, its inorder successor is 20; given the node with value 25, its inorder successor is null. given the node with value 9, its inorder successor is 11.
internal class TreeNode
{
public int Value { get; set; }
public TreeNode Left { get; set; }
public TreeNode Right { get; set; }
public TreeNode(int number)
{
Value = number;
}
}
20
/ \
9 25
/ \
5 12
/\
11 14
5 9 11 12 14 20 25
TreeNode FindLeastChild(TreeNode cur) {
while (cur.Left != null) {
cur = cur.Left;
}
return cur;
}
TreeNode FindBinarySearchTreeInOrderSuccessor(TreeNode root, TreeNode givenNode)
{
TreeNode parent = null;
TreeNode cur = root;
while (cur && cur.Value != givenNode.Value) {
if (cur.Value > givenNode.Value) {
parent = cur;
cur = cur.Left;
} else {
cur = cur.Right;
}
}
if (cur == null) {
// givenNode is not in the tree!
return null;
}
if (cur.Right != null) {
parent = cur.Right;
}
return FindLeastChild(parent);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment