Skip to content

Instantly share code, notes, and snippets.

@Turskyi
Created May 5, 2022 18:41
Show Gist options
  • Save Turskyi/b34548971bb5abce7d4094ce646abfbc to your computer and use it in GitHub Desktop.
Save Turskyi/b34548971bb5abce7d4094ce646abfbc to your computer and use it in GitHub Desktop.
Given the reference to a binary search tree and a value to insert, return a reference to the root of the tree after the value has been inserted in a position that adheres to the invariants of a binary search tree.
fun insertIntoBST(
root: TreeNode?, value: Int
): TreeNode? {
if (root == null) {
return TreeNode(value)
} else if (root.`val` < value) {
root.right = insertIntoBST(root.right, value)
} else if (root.`val` > value) {
root.left = insertIntoBST(root.left, value)
}
return root
}
/*
You are given the root node of a binary search tree (BST) and a value to insert into the tree.
Return the root node of the BST after the insertion.
It is guaranteed that the new value does not exist in the original BST.
Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion.
You can return any of them.
Example:
Given the following tree and value…
2
/ \
1 3
value = 4, return the following tree...
2
/ \
1 3
\
4
* */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment