Created
March 12, 2017 09:55
-
-
Save vitkarpov/f1250adc5c6bedf7bae794275931a628 to your computer and use it in GitHub Desktop.
Recursive inserting a node into a binary search tree
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
/** | |
* Рекурсивно проходится по бинарному дереву от корня, | |
* пока не найдет подходящее место для нового узла. | |
* Каждая вставка требует обход дерева, т.е. 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