树中节点的递归搜索

时间:2016-12-02 19:56:26

标签: recursion rust

我想使用两个结构构建一个树:NodeTree,然后从树中递归搜索目标节点。如果找到目标,请返回true,否则返回false

这里的挑战是如何递归调用find函数,因为它仅在Tree而不是Node上定义。

pub struct Node<T> {
    value: T,
    left: Option<Box<Node<T>>>,
    right: Option<Box<Node<T>>>,
}

pub struct Tree<T> {
    root: Option<Box<Node<T>>>,
}

impl<T: Ord> Tree<T> {
    /// Creates an empty tree
    pub fn new() -> Self {
        Tree { root: None }
    }

    // search the tree
    pub fn find(&self, key: &T) -> bool {
        let root_node = &self.root; // root is Option

        match *root_node {
            Some(ref node) => {

                if node.value == *key {
                    return true;
                }

                let target_node = if *key < node.value {
                    &node.left
                } else {
                    &node.right
                };

                match *target_node {
                    Some(sub_node) => sub_node.find(key),
                    None => {
                        return false;
                    } 
                }
            }
            None => return false,
        }
    }
}

fn main() {
    let mut mytree: Tree<i32> = Tree::new();

    let node1 = Node {
        value: 100,
        left: None,
        right: None,
    };
    let boxed_node1 = Some(Box::new(node1));

    let root = Node {
        value: 200,
        left: boxed_node1,
        right: None,
    };
    let boxed_root = Some(Box::new(root));
    let mytree = Tree { root: boxed_root };

    let res = mytree.find(&100);
}

当前代码报告错误:

error: no method named `find` found for type `Box<Node<T>>` in the current scope
  --> src/main.rs:36:48
   |
36 |                     Some(sub_node) => sub_node.find(key),
   |                                                ^^^^
   |
   = note: the method `find` exists but the following trait bounds were not satisfied: `Node<T> : std::iter::Iterator`
   = help: items from traits can only be used if the trait is implemented and in scope; the following traits define an item `find`, perhaps you need to implement one of them:
   = help: candidate #1: `std::iter::Iterator`
   = help: candidate #2: `core::str::StrExt`

我了解find仅在Tree上实施,因此存在错误,但我认为在{{1}上实施find效率很高}和Tree。有什么提示可以解决这个问题吗?

0 个答案:

没有答案