首页 > 解决方案 > 有没有办法交换 Rust 二叉搜索树中的节点?

问题描述

我正在研究 Rust 中的二叉搜索树实现,我正在尝试实现一个交换子节点的函数。

#[derive(Default)]
pub struct Node {
    data: i32,
    left: Option<Box<Node>>,
    right: Option<Box<Node>>
}

impl Node {
    fn print_data(&self) -> i32 {
        self.data
    }

    fn default() -> Node { //function to help when instantiate node with no children
        Node {
            data: 0,
            left: None,
            right: None
        }
    }

    fn set_left(&mut self, new_left: Option<Box<Node>>) -> () {
       // If self.left was already a pointer, now we're losing it
       // (memory leak).
       self.left = new_left
        // Node {data: self.data, left: new_left, right: &self.right}
    }
    fn set_right(&mut self, new_right: Option<Box<Node>>) -> () {
       self.right = new_right
    }

    fn swap_childs(&mut self) -> () {
        let tmpr = Some(self.right.unwrap());
        let tmpl = Some(self.left.unwrap());
        let nilr = self.right.take();
        let nill = self.left.take();
        self.right = tmpl;
        self.left = tmpr;
    }
}

这是我得到的错误:

error[E0507]: cannot move out of `self.right` which is behind a mutable reference
  --> src/main.rs:43:19
   |
43 |         let tmpr = Some(self.right.unwrap());
   |                         ^^^^^^^^^^
   |                         |
   |                         move occurs because `self.right` has type `std::option::Option<std::boxed::Box<Node>>`, which does not implement the `Copy` trait
   |                         help: consider borrowing the `Option`'s content: `self.right.as_ref()`

error[E0507]: cannot move out of `self.left` which is behind a mutable reference
  --> src/main.rs:44:19
   |
44 |         let tmpl = Some(self.left.unwrap());
   |                         ^^^^^^^^^
   |                         |
   |                         move occurs because `self.left` has type `std::option::Option<std::boxed::Box<Node>>`, which does not implement the `Copy` trait
   |                         help: consider borrowing the `Option`'s content: `self.left.as_ref()`

通过大量的试验和错误,我知道我的结构无法实现Copy特征,因为我使用的是Option. 这就是为什么我认为进行这种更改的最佳方法是在结构内,因此是 impl 函数swap_childs。有一个更好的方法吗?这个功能甚至可以使用OptionBox不使用其他类型Rc吗?

标签: rustbinary-search-tree

解决方案


推荐阅读