Skip to content

Instantly share code, notes, and snippets.

@vitkarpov
Created March 12, 2017 09:55
Show Gist options
  • Save vitkarpov/f1250adc5c6bedf7bae794275931a628 to your computer and use it in GitHub Desktop.
Save vitkarpov/f1250adc5c6bedf7bae794275931a628 to your computer and use it in GitHub Desktop.
Recursive inserting a node into a binary search tree
/**
* Рекурсивно проходится по бинарному дереву от корня,
* пока не найдет подходящее место для нового узла.
* Каждая вставка требует обход дерева, т.е. O(log N),
* поэтому время работы для создания бинарного дерева O(n * log N)
*/
function insertNodeIntoBST(root, node) {
if (root.data < node.data) {
if (root.right === null) {
root.right = node;
} else {
insertNodeIntoBST(root.right, node);
}
} else {
if (root.left === null) {
root.left = node;
} else {
insertNodeIntoBST(root.left, node);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment