【发布时间】:2022-11-11 05:22:52
【问题描述】:
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))));
}
}
我正在尝试通过解决一些 leet 代码问题来学习 rust。我正在尝试为二叉树实现插入功能。这是 leet 代码中给出的结构。我正在尝试通过传递路径的字符串列表来实现插入,例如。向左,向右,向左等。最后遍历后,我将添加新节点。我正在尝试使用 cur 节点作为临时指针,并希望使用每个字符串更改它。但每次我收到此错误时 - “临时值在借用时下降,请考虑使用 let 绑定来创建更长寿命的值”。我该如何解决这个问题并实施 insert ?
货物检查 -
【问题讨论】:
-
请始终包含来自
cargo check的完整错误。 -
不幸的是,我认为
RefCell无法实现您想要的。可以通过其他方式(例如Box的普通所有权)或通过递归。 -
@RadhikaGokani 请以文字而非图片的形式上传。
-
Learning Rust with Entirely Too Many Linked Lists 将回答您的所有问题以及更多问题,因为每个“借用问题”都会显示并(大部分)在那里解决,说为什么事情发生在每一步。阅读也很有趣。
标签: rust binary-tree