I'm trying to implement an algorithm for insertion into BST (binary search tree) in Rust. I did it recursively, but am having problems implementing the iterative solution. I'm struggling to borrow a child mutably when iterating.
I'm probably approaching it wrong and am looking for cues what's the best idiomatic way of writing such an algorithm.
Notes:
- I'd like to avoid cloning the nodes (unless it's
Rc::clone()). - It's a problem from LeetCode so the signature and types cannot be changed
Code (In Rust playground)
use std::cell::RefCell;
use std::rc::Rc;
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
// Returns the (possibly new) root of the tree
fn insert_into_bst_iterative(
root: Option<Rc<RefCell<TreeNode>>>,
val: i32,
) -> Option<Rc<RefCell<TreeNode>>> {
let mut root = root;
let mut cur_node = &mut root;
while let Some(cur_node_rc) = cur_node {
let mut cur_node_inner = cur_node_rc.borrow_mut();
if val <= cur_node_inner.val {
cur_node = &mut cur_node_inner.left;
} else {
cur_node = &mut cur_node_inner.right;
}
}
cur_node.replace(Rc::new(RefCell::new(TreeNode {
val,
left: None,
right: None,
})));
return root;
}
Error
Compiling playground v0.0.1 (/playground)
error[E0597]: `cur_node_inner` does not live long enough
--> src/lib.rs:21:29
|
18 | while let Some(cur_node_rc) = cur_node {
| -------- borrow later used here
19 | let mut cur_node_inner = cur_node_rc.borrow_mut();
| ------------------ binding `cur_node_inner` declared here
20 | if val <= cur_node_inner.val {
21 | cur_node = &mut cur_node_inner.left;
| ^^^^^^^^^^^^^^ borrowed value does not live long enough
...
25 | }
| - `cur_node_inner` dropped here while still borrowed
For more information about this error, try `rustc --explain E0597`.
error: could not compile `playground` (lib) due to 1 previous error