OCaml: Binary Search Tree Insertion (Recursive)
(* OCaml implementation of Binary Search Tree (BST) insertion using recursion. *) (* Define the structure for a BST node. *) type 'a bst_node = | Empty | Node of 'a * 'a bst_node * 'a bst_node (* Helper function to create a new node. *) let create_node value left right = Node (va...
This OCaml code defines and implements insertion into a Binary Search Tree (BST) using a recursive approach. A BST is a data structure where each node has at most two children, referred to as the left child and the right...
The provided OCaml code implements recursive insertion into a Binary Search Tree (BST). The `bst_node` type is defined as either `Empty` or a `Node` containing a value and two child BSTs. The `insert` function takes a value and a tree, returning a new tree with the value inserted. The base case for the recursion is when the tree is `Empty`; in this scenario, a new `Node` is created with the given value and two `Empty` children. For a non-empty `Node`, the function compares the `value` to be inserted with the `node_value`. If `value` is smaller, it recursively calls `insert` on the `left` subtree. If `value` is larger, it recursively calls `insert` on the `right` subtree. If `value` is equal to `node_value`, the tree remains unchanged to ensure unique values. The `create_node` helper constructs a new node, ensuring immutability by returning a new tree structure rather than modifying existing nodes. The time complexity for insertion in a balanced BST is O(log n), where n is the number of nodes. However, in the worst case (a skewed tree), it can degrade to O(n). The space complexity is O(log n) for a balanced tree due to the recursion stack, and O(n) for a skewed tree. Edge cases like inserting into an empty tree, inserting smaller/larger values than existing ones, and handling duplicates are addressed.
type bst_node: Empty Node(value, left_child, right_child) function insert(value, tree): if tree is Empty: return Node(value, Empty, Empty) else: node_value = tree.value left_child = tree.left_child right_child = tree.rig...