BST Insert And Delete With Successor (Rust)
Implement a Rust binary search tree supporting insert and search using in-order successor for delete.
Code
use std::cell::RefCell;
use std::rc::Rc;
type NodeRef = Option<Rc<RefCell<TreeNode>>>;
#[derive(Default)]
struct TreeNode { val: i32, left: NodeRef, right: NodeRef }
struct BST { root: NodeRef }
impl BST {
fn new() -> Self { Self { root: None } }
fn insert(&mut self, val: i32) {
let new_node = Some(Rc::new(RefCell::new(TreeNode { val, ..Default::default() })));
if self.root.is_none() { self.root = new_node; return; }
let mut cur = self.root.clone().unwrap();
loop {
let node = cur.borrow();
if val < node.val { if node.left.is_none() { drop(node); cur.borrow_mut().left = new_node; return; } let next = node.left.clone().unwrap(); drop(node); cur = next; }
else { if node.right.is_none() { drop(node); cur.borrow_mut().right = new_node; return; } let next = node.right.clone().unwrap(); drop(node); cur = next; }
}
}
}What the code does
BST Insert And Delete With Successor (Rust) keeps everything in the functions new and insert.
Applying it
The main signature reads fn new() -> Self
new is the public entry point; everything else in the file exists to support it.
Statements that matter
fn new() -> Self { Self { root: None } }
let new_node = Some(Rc::new(RefCell::new(TreeNode { val, ..Default::default() })));
let mut cur = self.root.clone().unwrap();
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
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. Every import resolves inside the standard library — `std::cell`, `std::rc`. The file defines `new`, `insert` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.