Created
January 3, 2018 07:44
-
-
Save jianminchen/a2608fd89cc8cad13df90a84747ce53a to your computer and use it in GitHub Desktop.
10 minutes solution - mock interview - iterative solution
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
/* | |
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