Created
June 24, 2018 00:40
-
-
Save revanth0212/0a44595cf7ffe0fd6d84e2fbdd6677bd to your computer and use it in GitHub Desktop.
Find the In-Order Successor of a node in a BST.
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
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