我具有以下树结构:
use std::cell::RefCell;
use std::rc::Rc;
use std::cmp;
use std::cmp::Ordering;
type AVLTree<T> = Option<Rc<RefCell<TreeNode<T>>>>;
#[derive(Debug, PartialEq, Clone)]
struct TreeSet<T: Ord> {
root: AVLTree<T>,
}
impl<T: Ord> TreeSet<T> {
fn new() -> Self {
Self {
root: None
}
}
fn insert(&mut self, value: T) -> bool {
let current_tree = &mut self.root;
while let Some(current_node) = current_tree {
let node_key = ¤t_node.borrow().key;
match node_key.cmp(&value) {
Ordering::Less => { let current_tree = &mut current_node.borrow_mut().right; },
Ordering::Equal => {
return false;
}
Ordering::Greater => { let current_tree = &mut current_node.borrow_mut().left; },
}
}
*current_tree = Some(Rc::new(RefCell::new(TreeNode {
key: value,
left: None,
right: None,
parent: None
})));
true
}
}
#[derive(Clone, Debug, PartialEq)]
struct TreeNode<T: Ord> {
pub key: T,
pub parent: AVLTree<T>,
left: AVLTree<T>,
right: AVLTree<T>,
}
fn main() {
let mut new_avl_tree: TreeSet<u32> = TreeSet::new();
new_avl_tree.insert(3);
new_avl_tree.insert(5);
println!("Tree: {:#?}", &new_avl_tree);
}
使用cargo build
构建很好,但是当我运行cargo run
时,出现以下错误:
线程'main'在'已经借用时感到恐慌:BorrowMutError',src \ libcore \ result.rs:1165:5
注意:使用
RUST_BACKTRACE=1
环境变量运行以显示回溯。错误:流程没有成功退出:
target\debug\avl-tree.exe
(退出代码:101)
如果我只打电话给insert(3)
,那很好,我的树可以正确打印。但是,如果我在insert(5)
之后输入insert(3)
,则会收到该错误。
我该如何解决?
由于语言上的内存安全规则,对于新手来说,手动实现诸如链表,树,图之类的数据结构不是任务。我建议您阅读Too Many Linked Lists教程,该教程讨论如何以Rust正确的方式实现安全列表和不安全链接列表。
首先让我们更正您的算法。以下几行不正确: