Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

#![allow(unused)]
fn main() {
use std::cmp::Ord;
use std::boxed::Box;

#[derive(Debug)]
struct TreeNode<T> {
    val: T,
    left: Option<Box<TreeNode<T>>>,
    right: Option<Box<TreeNode<T>>>,
}

#[derive(Debug)]
pub struct BST<T> {
    root: Option<Box<TreeNode<T>>>,
}


impl<T: Ord> TreeNode<T> {
    fn new(val: T) -> Self {
        TreeNode {
            val,
            left: None,
            right: None,
        }
    }

    fn insert(&mut self, val: T) {
        if val < self.val {
            match self.left {
                Some(ref mut left_node) => left_node.insert(val),
                None => self.left = Some(Box::new(TreeNode::new(val))),
            }
        } else if val > self.val {
            match self.right {
                Some(ref mut right_node) => right_node.insert(val),
                None => self.right = Some(Box::new(TreeNode::new(val))),
            }
        }
        // Duplicate values are ignored
    }
}

impl<T: Ord> BST<T> {
    pub fn new() -> Self {
        BST { root: None }
    }

    pub fn insert(&mut self, val: T) {
        match self.root {
            Some(ref mut node) => node.insert(val),
            None => self.root = Some(Box::new(TreeNode::new(val))),
        }
    }
}
}