Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created January 3, 2018 07:44
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/a2608fd89cc8cad13df90a84747ce53a to your computer and use it in GitHub Desktop.
Save jianminchen/a2608fd89cc8cad13df90a84747ce53a to your computer and use it in GitHub Desktop.
10 minutes solution - mock interview - iterative solution
/*
Find binary search tree inorder successor - iterator solution
https://i.stack.imgur.com/OWd4M.jpg
binary search tree
14's inorder successor is 20
9's 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;
}
}
public static TreeNode FindBinarySearchTreeInOrderSuccessor(TreeNode root, TreeNode givenNode)
inorder successor
# if givenNode->right != NULL
givenNode = givenNode->right
while (givenNode->left != NULL)
givenNode = givenNode->left
return givenNode
else
list = []
currentNode = root
while (currentNode != givenNode)
if currentNode->val > givenNode->val:
list.append(currentNode, true)
currentNode = currentNode->left
else:
list.append(currentNode, false)
currentNode = currentNode->right
for i in xrange(len(list)-1, -1, -1):
if list[i][2] is True:
return list[i][1]
[(20, true), (9, false), (12, false)]
20
/ \
9 25
/ \
5 12
/ \
11 14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment