A Binary Search Tree (BST) is a hierarchical data structure where each node has at most two children. For any node, all elements in the left subtree are smaller, and all elements in the right subtree are larger.
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def insert(node, key):
if node is None:
return Node(key)
if key < node.val:
node.left = insert(node.left, key)
else:
node.right = insert(node.right, key)
return node
class Node {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
function insert(root, val) {
if (!root) return new Node(val);
if (val < root.val) {
root.left = insert(root.left, val);
} else {
root.right = insert(root.right, val);
}
return root;
}