This is a JavaScript implementation of a Binary Search Tree (BST), which provides various methods for manipulating and traversing binary search trees.
Please note: this implementation doesn't allow duplicates.
- Creates a new BST instance with elements from passed array after removing duplicates.
- Getter method to retrieve the root node of the BST.
- Getter method to calculate and return the height of the BST.
- Adds a new node with the specified value to the BST.
- Balances the tree if it becomes unbalanced after insertion.
- Deletes the node with the specified value from the BST.
- Searches for a node with the specified value in the BST.
- Returns the node if found, otherwise returns
null
.
- Performs a breadth-first traversal of the BST.
- If a callback function is provided, it is called with each node's value during traversal.
- Returns an array of node values in level-order if no callback is provided.
- Performs an in-order traversal of the BST.
- If a callback function is provided, it is called with each node's value during traversal.
- Returns an array of node values in in-order if no callback is provided.
- Performs a pre-order traversal of the BST.
- If a callback function is provided, it is called with each node's value during traversal.
- Returns an array of node values in pre-order if no callback is provided.
- Performs a post-order traversal of the BST.
- If a callback function is provided, it is called with each node's value during traversal.
- Returns an array of node values in post-order if no callback is provided.
- Checks whether the BST is balanced (i.e., the height difference between the left and right subtrees is at most 1).
- Returns
true
if the tree is balanced, otherwise returnsfalse
.
- Replances and returns the rebalanced BST instance.
- Prints the BST structure to the console in a readable format.
// Import the BinarySearchTree class
import BinarySearchTree from "./BinarySearchTree.js";
// Create a new BST instance
const bst = new BinarySearchTree([5, 3, 7, 2, 4, 6, 8]);
// Perform operations on the BST
bst.add(9);
bst.delete(4);
// Print the BST structure
bst.print();
// Perform traversal
const inOrderTraversal = bst.inOrder();
console.log("In-order traversal:", inOrderTraversal);
// Or define a callback function to be used with inOrder method
const callback = (value) => {
console.log(value); // Print each node's value during traversal
};
// Perform in-order traversal with the callback
console.log("In-order traversal with callback:");
bst.inOrder(callback);
- This implementation relies on the
Node
class and theQueue
class, which should be imported from separate files (node.js
andqueue.js
).