如何解决遍历BST时借入的临时值下降
use std::{cell::RefCell,rc::Rc};
#[derive(Debug,PartialEq,Eq)]
pub struct TreeNode {
pub val: i32,pub left: Option<Rc<RefCell<TreeNode>>>,pub right: Option<Rc<RefCell<TreeNode>>>,}
fn find_min(mut node: &Option<Rc<RefCell<TreeNode>>>) -> i32 {
while node.as_ref().unwrap().borrow().left.is_some() {
node = &node.as_ref().unwrap().borrow().left;
}
node.as_ref().unwrap().borrow().val
}
error[E0716]: temporary value dropped while borrowed
--> src/lib.rs:12:17
|
10 | fn find_min(mut node: &Option<Rc<RefCell<TreeNode>>>) -> i32 {
| - let's call the lifetime of this reference `'1`
11 | while node.as_ref().unwrap().borrow().left.is_some() {
12 | node = &node.as_ref().unwrap().borrow().left;
| --------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^------ temporary value is freed at the end of this statement
| | |
| | creates a temporary which is freed while still in use
| assignment requires that borrow lasts for `'1`
TreeNode
已给出,无法更改。
我了解为什么会收到错误,但不知道如何解决。
解决方法
更新:
使用Rc
作为参数看起来更好:
use std::rc::Rc;
#[derive(Debug,PartialEq,Eq)]
pub struct TreeNode {
pub val: i32,pub left: Option<Rc<TreeNode>>,pub right: Option<Rc<TreeNode>>,}
pub fn find_min(mut current: Rc<TreeNode>) -> i32 {
while current.left.is_some() {
current = Rc::clone(current.left.as_ref().unwrap());
}
current.val
}
fn main() {
let left_child = TreeNode {
val: 1,left: None,right: None,};
let root = TreeNode {
val: 6,left: Some(Rc::new(left_child)),};
println!("min: {}",find_min(Rc::new(root)));
}
RefCell
和mut
东西对我来说似乎多余?
那:
use std::rc::Rc;
#[derive(Debug,}
pub fn find_min(root: &TreeNode) -> i32 {
let mut current = Rc::new(root);
while current.left.is_some() {
current = Rc::new(current.left.as_ref().unwrap());
}
current.val
}
,
根据this answer编写我的解决方案:
fn find_min(node: &Option<Rc<RefCell<TreeNode>>>) -> i32 {
let mut curr = node.as_ref().unwrap().clone();
while curr.borrow().left.is_some() {
let tmp = curr.borrow().left.as_ref().unwrap().clone();
curr = tmp;
}
let res = curr.borrow().val;
res
}
这两个临时变量看起来都不好,但这就是事实。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。