我正在尝试用 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,
}
}
}
如果我想进行中序遍历,如何解包TreeNode
的 Option<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() {}
( Playground )
编译器提示:
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
最佳答案
Unwrap and access
T
from anOption<Rc<RefCell<T>>>
您真的不想尝试从 Option
中删除值, Rc
或 RefCell
通过unwrap
/try_unwrap
/into_inner
.相反,Option
上的模式匹配然后调用borrow
在 RefCell
上获得对 T
的引用.
另外:
- 使用
if let
而不是match
当您只关心一只 ARM 时的声明。 - 变量使用
snake_case
.V
不是一个合适的名字。 - 这里不需要使用结构,也不需要公开定义辅助函数。普通函数和嵌套函数更简单,公开的细节也更少。
- 构造
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
}
}
另见:
关于rust - 从 Option<Rc<RefCell<T>>> 解包并访问 T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54012660/