Binary Search Tree : Insertion

Sort by

recency

|

579 Discussions

|

  • + 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.

  • + 0 comments

    My Java 8 Solution

    public static Node insert(Node root,int data) {
            Node newNode = new Node(data);
            
            if (root == null) {
                return newNode;
            }
            
            Node current = root;
        	root = current;
            
            while (true) {
                if (data > current.data) {
                    if (current.right == null) {
                        current.right = newNode;
                        return root;
                    } else {
                        current = current.right;
                    }
                } else if (data < current.data) {
                    if (current.left == null) {
                        current.left = newNode;
                        return root;
                    } else {
                        current = current.left;
                    }
                }
            }
        }
    
  • + 0 comments

    if(root == null) { root = new Node(data); } else if(data < root.data) { root.left = insert(root.left, data); } else { root.right = insert(root.right, data); } return root;