use std::cell::RefCell;
use std::rc::Rc;
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
pub fn invalid_path_error(self) {
panic!("Invalid path");
}
pub fn insert(&mut self, directions: &[&str], val: i32) {
let mut cur_node = &mut None;
let l = directions.len();
if directions[0] == "left" {
cur_node = &mut self.left;
}
if directions[0] == "right" {
cur_node = &mut self.right;
}
for dir in &directions[1..] {
let mut n;
if *dir == "left" {
if let Some(z) = cur_node {
n = &mut z.borrow_mut().left;
} else {
panic!("Invalid path");
}
}
if *dir == "right" {
if let Some(z) = cur_node {
n = &mut z.borrow_mut().right;
} else {
panic!("Invalid path");
}
}
cur_node = n;
}
//cur_node = Some(Rc::new(RefCell::new(TreeNode::new(2))));
}
}
I am trying to learn rust by solving some leet code questions. I am trying to implement insert function for binary tree. This is the struct given in leet code. I am trying to implement insert by pass list of strings for path For eg. go left , right , left etc. After traversing at the end I will add new node. I am trying to use cur node as a temp pointer and want to change it with each string. But every time I get this error - " temporary value dropped while borrowed consider using a let binding to create a longer lived value ". How can I fix this and implement insert ?
cargo check -
