从选项<Rc<RefCell解包和访问T<T>>>



我正在尝试用Rust解决一些Leetcode问题。然而,我在LeetCode的TreeNode实现中遇到了一些困难。

use std::cell::RefCell;
use std::rc::Rc;
// TreeNode data structure
#[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,
}
}
}

如果我想进行有序遍历,如何打开TreeNodeOption<Rc<RefCell<TreeNode>>>对象,访问其.val.left.right,并将它们作为输入传递到递归函数中?

我试过:

pub struct Solution;
impl Solution {
pub fn inorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut ret: Vec<i32> = vec![];
match root {
Some(V) => Solution::helper(&Some(V), &mut ret),
None => (),
}
ret
}
fn helper(node: &Option<Rc<RefCell<TreeNode>>>, ret: &mut Vec<i32>) {
match node {
None => return,
Some(V) => {
// go to the left branch
Solution::helper(
(*Rc::try_unwrap(Rc::clone(V)).unwrap_err())
.into_inner()
.left,
ret,
);
// push root value on the vector
ret.push(Rc::try_unwrap(Rc::clone(V)).unwrap_err().into_inner().val);
// go right branch
Solution::helper(
(*Rc::try_unwrap(Rc::clone(V)).unwrap_err())
.into_inner()
.right,
ret,
);
}
}
}
}
fn main() {}

(游乐场)

编译器抱怨:

error[E0308]: mismatched types
--> src/lib.rs:42:21
|
42 | /                     (*Rc::try_unwrap(Rc::clone(V)).unwrap_err())
43 | |                         .into_inner()
44 | |                         .left,
| |_____________________________^ expected reference, found enum `std::option::Option`
|
= note: expected type `&std::option::Option<std::rc::Rc<std::cell::RefCell<TreeNode>>>`
found type `std::option::Option<std::rc::Rc<std::cell::RefCell<TreeNode>>>`
help: consider borrowing here
|
42 |                     &(*Rc::try_unwrap(Rc::clone(V)).unwrap_err())
43 |                         .into_inner()
44 |                         .left,
|

但如果我尝试这个建议,它也会抱怨:

error[E0507]: cannot move out of an `Rc`
--> src/lib.rs:42:22
|
42 |                     &(*Rc::try_unwrap(Rc::clone(V)).unwrap_err())
|                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot move out of an `Rc`
error[E0507]: cannot move out of data in a `&` reference
--> src/lib.rs:42:22
|
42 |                     &(*Rc::try_unwrap(Rc::clone(V)).unwrap_err())
|                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|                      |
|                      cannot move out of data in a `&` reference
|                      cannot move

展开并从Option<Rc<RefCell<T>>>访问T

您确实不想尝试通过unwrap/try_unwrap/into_innerOptionRcRefCell中删除该值。相反,在Option上进行模式匹配,然后在RefCell上调用borrow以获得对T的引用。

另外:

  1. 如果只关心一只手臂,请使用if let而不是match语句
  2. 变量使用snake_caseV不是一个合适的名称
  3. 这里不需要使用结构,也不需要公开定义helper函数。纯函数和嵌套函数更简单,公开的细节更少
  4. 在构造ret时,不需要提供显式类型
pub fn inorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
fn helper(node: &Option<Rc<RefCell<TreeNode>>>, ret: &mut Vec<i32>) {
if let Some(v) = node {
let v = v.borrow();
helper(&v.left, ret);
ret.push(v.val);
helper(&v.right, ret);
}
}
let mut ret = vec![];
if let Some(v) = root {
helper(&Some(v), &mut ret);
}
ret
}

就我个人而言,我不喜欢被迫构建Some,所以我可能会重新组织代码,这也允许我将其作为方法粘贴在TreeNode:上

impl TreeNode {
pub fn inorder_traversal(&self) -> Vec<i32> {
fn helper(node: &TreeNode, ret: &mut Vec<i32>) {
if let Some(ref left) = node.left {
helper(&left.borrow(), ret);
}
ret.push(node.val);
if let Some(ref right) = node.right {
helper(&right.borrow(), ret);
}
}
let mut ret = vec![];
helper(self, &mut ret);
ret
}
}

另请参阅:

  • 为什么Arc::try_unwrap()会引起恐慌

相关内容

  • 没有找到相关文章

最新更新