Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Last active December 12, 2015 05:18
Show Gist options
  • Save charlespunk/4720296 to your computer and use it in GitHub Desktop.
Save charlespunk/4720296 to your computer and use it in GitHub Desktop.
Write an algorithm to find the 'next' node (i.e., in-order successor) of a given node in a binary search tree. You may assume that each node has a link to its parent.
//in-order
public static Node findNextInOrderNodeBST(Node root){
if(root == null) return null;
if(root.right != null){
Node firstLeft = root.right;
while(firstLeft.left != null){
firstLeft = firstLeft.left;
}
return firstLeft;
}
else{
Node thisParent = root.thisParent;
while(thisParent != null && thisParent.value < root.value){
thisParent = thisParent.parent;
}
return thisParent;
}
}
//pre-order
public static Node findNextPreOrderNodeBST(Node root){
if(root == null) return null;
if(root.left != null) return root.left;
else if(root.right != null) return root.right;
else{
Node thisParent = root.parent;
while(thisParent != null && (thisParent.value < root.value || thisParent.right == null)){
thisParent = thisParent.parent;
}
if(thisParent == null) return null;
else return thisParent.right;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment