Last active
December 12, 2015 05:18
-
-
Save charlespunk/4720296 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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. |
This file contains hidden or 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
//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; | |
} | |
} | |
This file contains hidden or 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
//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