我正在尝试用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
的{{1}}对象,访问其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() {}
但是,如果我尝试该建议,它也会抱怨:
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,
|
答案 0 :(得分:1)
展开并从选项访问T >>
您真的不想通过Option
从Rc
,RefCell
或unwrap
中删除值/ try_unwrap
/ into_inner
。而是在Option
上进行模式匹配,然后在borrow
上调用RefCell
以获取对T
的引用。
另外:
if let
而不是match
语句。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
上:< / p>
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
}
}
另请参阅: