Created
August 13, 2024 03:54
-
-
Save kshirish/68d77dcdd07b6654c8144cd4c8cb45fe to your computer and use it in GitHub Desktop.
Binary Tree Array - Insert, Delete
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
function insert(tree, value) { | |
tree.push(value); | |
return tree; | |
} | |
function deleteNode(tree, value) { | |
const index = tree.indexOf(value); | |
if (index === -1) { | |
return tree; | |
} | |
// Swap with the last node | |
tree[index] = tree[tree.length - 1]; | |
// Remove the last node | |
tree.pop(); | |
return tree; | |
} | |
let tree = []; | |
tree = insert(tree, 10); | |
tree = insert(tree, 5); | |
tree = insert(tree, 15); | |
tree = insert(tree, 2); | |
tree = insert(tree, 7); | |
console.log("Tree after insertions:", tree); | |
// Output: [10, 5, 15, 2, 7] | |
tree = deleteNode(tree, 5); | |
console.log("Tree after deleting 5:", tree); | |
// Output could be: [10, 7, 15, 2] depending on how the last element was moved |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment