Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created December 28, 2017 22:14
Show Gist options
  • Save jianminchen/9a9d0856b6e4a719534bc00388fa8f9e to your computer and use it in GitHub Desktop.
Save jianminchen/9a9d0856b6e4a719534bc00388fa8f9e to your computer and use it in GitHub Desktop.
Binary search tree inorder successor - JavaScript
// internal class TreeNode
// {
// public int Value { get; set; }
// public TreeNode Left { get; set; }
// public TreeNode Right { get; set; }
// public TreeNode(int number)
// {
// Value = number;
// }
// }
// FindBinarySearchTreeInOrderSuccessor(TreeNode root, TreeNode givenNode)
// Given the node with value 14, its inorder successor is 20; given the node with value 25, its inorder successor is null.
// given the node with value 9, its inorder successor is 11.
// If givenNode has children:
// Look at the first right child of givenNode (to find highervalue)
// If right child is givenNode.value + 1, return
// Else look at the subsequent left child of node on every recursive call
// Keep looking at left child until I find a node with no left child
// => return node
// If the givenNode has no child (leaf node):
// Start at rootNode
// If givenNode.value < rootNode.value
// look at left Child
// if node (leftChild) < givenNode.value
// look at rightChild
// return parent
function Node (val) {
this.value = val;
this.left = null;
this.right = null;
}
const rootNode = new Node(20);
const left1 = new Node(9);
const right1 = new Node(25);
const left2 = new Node(5);
const right2 = new Node(12);
const left3 = new Node(11);
const right3 = new Node(14);
rootNode.left = left1;
rootNode.right = right1;
left1.left = left2;
left1.right = right2;
left2.left = left3;
left2.right = right3;
// Test using repl.it
let newHigherNodeVal = 0;
function findInOrderSuccessor(rootNode, givenNode, currNode = givenNode) {
if (rootNode.value === givenNode.value) return rootNode.right || 'No bigger node';
if (currNode.right) { // if node is not leafNode
newHigherNodeVal = givenNode.right.value;
return findInOrderSuccessor(rootNode, givenNode, givenNode.right);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment