Created
December 25, 2022 05:30
-
-
Save thmain/306273e42bbd47f3765f2944eb1690b1 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
'use strict'; | |
function inOrderSuccessor(node) { | |
if (!node) { | |
return null; | |
} | |
if (node.right) { | |
return leftMostChild(node.right); | |
} else { | |
var currentNode = node; | |
// Assuming each node has a reference to its parent | |
var parentNode = currentNode.parent; | |
// Go up until we find deepest ancestor for which node would be in left sub tree | |
while (parentNode && parentNode.left !== currentNode) { | |
currentNode = parentNode; | |
parentNode = parentNode.parent; | |
} | |
return parentNode; | |
} | |
} | |
function leftMostChild(node) { | |
if (!node) { | |
return null; | |
} | |
while (node.left) { | |
node = node.left; | |
} | |
return node; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment