Binary Search Tree : Insertion

Sort by

recency

|

581 Discussions

|

  • + 0 comments

    Python:

        def add_to_node(self, node, val): 
            if val<node.info:
                if node.left is None: 
                    node.left=Node(val)
                else:
                    self.add_to_node(node.left, val)
            elif val>node.info:
                if node.right is None: 
                    node.right=Node(val)
                else:
                    self.add_to_node(node.right, val)
    
        def insert(self, val):
            if self.root is None: 
                self.root=Node(val)
            else:
                self.add_to_node(self.root, val)
    
  • + 0 comments
    Node * insert(Node * root, int data) {
            
            if (!root) {
                return new Node(data);
            }
            
            if (data < root->data) {
                root->left = insert(root->left, data);
            } else {
                root->right = insert(root->right, data);
            }
    
            return root;
        }
    
  • + 0 comments

    Java:

    public static Node insert(Node root,int data) {
        Node n = new Node(data);
        Node head = root;
        if (root == null) {
            root = n;
        }
        while (head != null) {
            if (data < head.data && head.left == null) {
                head.left = n;
                break;
            } else if (data < head.data && head.left != null) {
                head = head.left;
            } else if (data >= head.data && head.right != null) {
                head = head.right;
            } else if (data >= head.data && head.right == null) {
                head.right = n;
                break;
            }
        }
        return root;
    }
    
  • + 0 comments

    Doesn't seem to work properly in JavaScript.

  • + 0 comments

    I’ve been learning BST insertion to improve how my script executor handles commands. If you're into Roblox scripting, Delta Executor uses similar logic to run scripts smoothly — worth checking out for automation ideas.