Skip to content

Instantly share code, notes, and snippets.

@revanth0212
Created June 24, 2018 00:40
Show Gist options
  • Save revanth0212/0a44595cf7ffe0fd6d84e2fbdd6677bd to your computer and use it in GitHub Desktop.
Save revanth0212/0a44595cf7ffe0fd6d84e2fbdd6677bd to your computer and use it in GitHub Desktop.
Find the In-Order Successor of a node in a BST.
class Stack {
constructor(root) {
this.stack = []
while (root) {
this.stack.push(root)
root = root.left
}
}
hasNext() {
return this.stack.length > 0
}
next(preload) {
var nextNode = this.stack.pop()
if (preload && nextNode && nextNode.right) {
var temp = nextNode.right
while(temp) {
this.stack.push(temp)
temp = temp.left
}
}
return nextNode
}
}
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {TreeNode} p
* @return {TreeNode}
*/
var inorderSuccessor = function(root, p) {
var stack = new Stack(root)
while(stack.hasNext()) {
if (stack.next(true).val === p.val) {
break
}
}
var returnValue = stack.next(false)
if (returnValue === undefined) {
return null
} else {
return returnValue
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment