Created
March 7, 2018 04:57
-
-
Save jianminchen/72e92d185eb749d4a3e6d8ec85b56184 to your computer and use it in GitHub Desktop.
BST successor search - March 6, 2018 - Julia practiced mock interview
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
using System; | |
class Solution | |
{ | |
public class Node | |
{ | |
public int value; | |
public Node left; | |
public Node right; | |
public Node parent; | |
} | |
public static Node findInOrderSuccessor(Node inputNode) | |
{ | |
if(inputNode == null) | |
return null; | |
if(inputNode.right != null) | |
{ | |
return getRightSubtreeSmallest(inputNode); | |
} | |
else | |
{ | |
findPossibleFirstParentBiggerThanGivenValue(inputNode); | |
} | |
} | |
public static Node getRightSubtreeSmallest(Node inputNode) | |
{ | |
var node = inputNode.right; | |
while(node.left != null) | |
{ | |
node = node.left; | |
} | |
return node; | |
} | |
public static Node findPossibleFirstParentBiggerThanGivenValue(Node inputNode) | |
{ | |
var start = inputNode.parent; | |
while(start.parent != null && start.parent < inputNode.value) | |
{ | |
start = start.parent; // start's value definitely will be smaller than given value | |
} | |
return start.parent; | |
} | |
static void Main(string[] args) | |
{ | |
} | |
} | |
/* | |
BST - 5 9 11 12 14 20 25 <- linear access O(1) -> inorder traversal time complexity: O(n) | |
next to give node value | |
given node is 9, find 11; | |
given node is 14, find 20; | |
- lgn - height of tree | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment