#[derive(Debug, Ord, PartialOrd, Eq, PartialEq)]
pub struct TreeNode {
pub val: i32,
pub left: Option>>,
pub right: Option>>,
}
impl TreeNode {
pub fn new(val: i32) -> TreeNode {
TreeNode {
val,
left: None,
right: None,
}
}
}
pub fn traverse_post(root: Option>>) -> Vec<i32> {
let mut vec = vec![];
dfs(root, &mut vec);
return vec;
fn dfs(node: Option>>, list: &mut Vec<i32>) {
if let Some(x)=node {
dfs(x.borrow().left.clone(), list);
list.push(x.borrow().val);
dfs(x.borrow().right.clone(),list);
}
}
}
这段代码在dfs中,x.borrow()那里一直报错,让我指定type annotation ,有人知道这该怎么解决吗,谢谢~
这可能是因为该行代码中没有指定变量x的类型,这样编译器无法判断它可以调用哪些方法。你可以尝试指定一下变量类型,比如let x: Option<Rc<RefCell>> = node; 或者let x: Rc<RefCell> = node.unwrap();,看编译器是否接受。
如果上述方法不行,你也可以尝试对x.borrow()调用as_ref()函数,用来将RefCell类型的引用转换为Ref类型的引用,然后再调用其中的方法来访问TreeNode的值。
这个问题是由于 x.borrow() 方法返回的是一个 Ref 类型的借用,而 Rust 不能确定这个借用是什么类型。
在这种情况下,你可以使用类型指示符 as 明确地告诉编译器这个借用是 TreeNode 类型。
let x = x.borrow() as &TreeNode;