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.
Code
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
Markdown Heading OutlineExtract ATX headings from Markdown into an indented outline with line numbers and per-level counts, ignoring code fences.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.