Created
January 20, 2018 19:56
-
-
Save jianminchen/7b0c94a34923dc9e2b44c41171c20aa4 to your computer and use it in GitHub Desktop.
binary search tree in order successor mock interview - Jan. 20, 2018
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
// 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