1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
use pyo3::prelude::*;
/// Represents a Node in a Binary Search Tree.
#[pyclass]
pub struct Node {
/// The value stored in the node.
value: i32,
/// The left child node.
left: Option<Box<Node>>,
/// The right child node.
right: Option<Box<Node>>,
}
#[pymethods]
impl Node {
/// Creates a new Node with the given value.
#[new]
fn new(value: i32) -> Self {
Node {
value,
left: None,
right: None,
}
}
/// Inserts a value into the Binary Search Tree.
///
/// If the value is less than the current node's value, it goes to the left;
/// otherwise, it goes to the right.
fn insert(&mut self, value: i32) {
if value < self.value {
match &mut self.left {
Some(node) => node.insert(value),
None => self.left = Some(Box::new(Node::new(value))),
}
} else {
match &mut self.right {
Some(node) => node.insert(value),
None => self.right = Some(Box::new(Node::new(value))),
}
}
}
/// Searches for a value in the Binary Search Tree.
///
/// Returns true if the value is found in the tree; otherwise, false.
fn search(&self, value: i32) -> bool {
if value == self.value {
true
} else if value < self.value {
match &self.left {
Some(node) => node.search(value),
None => false,
}
} else {
match &self.right {
Some(node) => node.search(value),
None => false,
}
}
}
}
/// Represents a Binary Search Tree (BST).
#[pyclass]
pub struct BinarySearchTree {
root: Option<Box<Node>>,
}
#[pymethods]
impl BinarySearchTree {
/// Creates a new empty Binary Search Tree (BST).
#[new]
fn new() -> Self {
BinarySearchTree {
root: None,
}
}
/// Inserts a value into the Binary Search Tree (BST).
///
/// If the tree is empty, creates a new root node with the given value.
/// Otherwise, recursively inserts the value into the appropriate position.
fn insert(&mut self, value: i32) {
if let Some(ref mut root) = self.root {
root.insert(value);
} else {
self.root = Some(Box::new(Node::new(value)));
}
}
/// Searches for a value in the Binary Search Tree (BST).
///
/// Returns true if the value is found in the tree; otherwise, false.
///
/// If the tree is empty, returns false.
fn search(&self, value: i32) -> bool {
if let Some(ref root) = self.root {
root.search(value)
} else {
false
}
}
}