GDScript: Binary Search Tree Node Insertion
class Node: var value var left = null var right = null func _init(val): value = val class BinarySearchTree: var root = null func insert(value): if root == null: root = Node.new(value) return _insert_recursive(root, value) func _insert_recursive(current_node, value): if value == c...
This GDScript code defines a Binary Search Tree (BST) with a recursive insertion method. The BST is a data structure where each node has at most two children, referred to as the left child and the right child. For any gi...
The `BinarySearchTree` class uses a `Node` class to represent each element in the tree, storing a `value` and references to its `left` and `right` children. The `insert` method is the public interface, handling the initial case where the tree is empty by creating the root node. For non-empty trees, it delegates the insertion logic to the private recursive helper function `_insert_recursive`. This helper function takes the current node and the value to be inserted. It first checks if the value already exists in the tree; if so, it returns without inserting to prevent duplicates. Otherwise, it compares the value with the current node's value. If the value is smaller, it attempts to insert into the left subtree; if the left child is null, a new node is created there. If the left child exists, the function recursively calls itself on the left child. A similar process occurs for values greater than the current node's value, targeting the right subtree. The recursion naturally handles traversing down the tree until an appropriate null child pointer is found for insertion. The time complexity for insertion in a balanced BST is O(log N), where N is the number of nodes, because the search path is logarithmic. In the worst case (a skewed tree), it degrades to O(N). The space complexity is O(log N) for a balanced tree and O(N) for a skewed tree due to the recursion depth.
class Node: value left = null right = null function Node(val): initialize node with val class BinarySearchTree: root = null function insert(value): if root is null: set root to new Node(value) return call _insert_recursi...