BST Insert And Delete With Successor (Java)

Implement a Java binary search tree supporting insert and delete using in-order successor for two-child nodes.

JavaData Integrity

Code

javasnippet
13 lines
public class BST {
    static class Node { int val; Node left, right; Node(int v) { val = v; } }
    Node root;
    public void insert(int val) {
        if (root == null) { root = new Node(val); return; }
        Node cur = root;
        while (true) {
            if (val < cur.val) { if (cur.left == null) { cur.left = new Node(val); return; } cur = cur.left; }
            else { if (cur.right == null) { cur.right = new Node(val); return; } cur = cur.right; }
        }
    }
    public boolean has(int val) { Node cur = root; while (cur != null) { if (val == cur.val) return true; cur = val < cur.val ? cur.left : cur.right; } return false; }
}

Inside the snippet

Count the classes BST and Node and the functions Node, insert and has as the entire surface area of BST Insert And Delete With Successor (Java).

Iteration happens inside while (true) — everything outside it runs once.

Putting it to use

The primary signature is static class Node { int val; Node left, right; Node(int v)

Core lines

if (val < cur.val) { if (cur.left == null) { cur.left = new Node(val); return; } cur = cur.left; }
else { if (cur.right == null) { cur.right = new Node(val); return; } cur = cur.right; }
if (root == null) { root = new Node(val); return; }

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. The file defines `Node`, `insert`, `has` at load time.