Skip to main content

TreeNode

Struct TreeNode 

Source
pub struct TreeNode<T> { /* private fields */ }
Expand description

A node in a tree structure that represents a single element with optional children.

The TreeNode struct is a fundamental building block for tree-based genetic programming in Radiate. It represents a node in a tree that can have zero or more child nodes, forming a hierarchical structure. Each node has a value of type T and maintains an optional list of child nodes.

§Type Parameters

  • T - The type of value stored in the node. This type must implement Clone, PartialEq, and other traits required by the genetic programming operations.

§Fields

  • value - The actual value stored in the node
  • arity - Optional Arity that specifies how many children the node can have
  • children - Optional vector of child nodes

§Examples

use radiate_gp::{collections::{TreeNode}, Arity, Node};

// Create a new node with value 42
let node = TreeNode::new(42);

// Create a node with specific arity
let node_with_arity = TreeNode::with_arity(42, Arity::Exact(2));
let other_node_with_arity = TreeNode::from((42, Arity::Exact(2)));

assert_eq!(node_with_arity.arity(), other_node_with_arity.arity());

// Create a node with children
let node_with_children = TreeNode::with_children(42, vec![
    TreeNode::new(1),
    TreeNode::new(2)
]);
let other_node_with_children = TreeNode::from((42, vec![
    TreeNode::new(1),
    TreeNode::new(2),
]));

§Node Types and Arity

The node’s type and arity determine its behavior and validity:

  • Leaf nodes have no children (arity is Arity::Zero)
  • Vertex nodes can have any number of children (arity is Arity::Any)
  • Root nodes are the starting point of the tree and can have any number of children

§Tree Operations

The struct provides several methods for tree manipulation:

  • new() - Creates a new node with no children
  • with_arity() - Creates a node with a specific arity
  • with_children() - Creates a node with a list of children
  • add_child() - Adds a child to the node
  • attach() - Attaches a child and returns self for method chaining
  • detach() - Removes a child at a specific index
  • swap_subtrees() - Swaps subtrees between two nodes

§Tree Traversal

The struct implements the TreeIterator trait, providing three traversal methods:

  • iter_pre_order() - Traverses the tree in pre-order (root, then children)
  • iter_post_order() - Traverses the tree in post-order (children, then root)
  • iter_breadth_first() - Traverses the tree level by level

§Tree Properties

The struct provides methods to query tree properties:

  • is_leaf() - Checks if the node has no children - must have Arity::Zero
  • size() - Returns the total number of nodes in the subtree
  • height() - Returns the height of the subtree

§Validity

A node is considered valid based on its arity:

§Implementation Details

The struct implements several traits:

  • Node - Provides common node behavior and access to value and type information
  • Gene - Enables genetic operations for the node making it compatible with genetic algorithms
  • Valid - Defines validity rules for the node
  • Debug - Provides debug formatting
  • Clone, PartialEq - Required for genetic programming operations
  • Format - Provides pretty-printing of the tree structure

§Evaluation

When T implements the Eval trait, the node can be evaluated with input data:

use radiate_gp::{Op, Eval, TreeNode};

let tree = TreeNode::new(Op::add())
    .attach(TreeNode::new(Op::constant(2.0)))
    .attach(TreeNode::new(Op::constant(3.0)));

let result = tree.eval(&[]); // Evaluates to 5.0

Implementations§

Source§

impl<T> TreeNode<T>

Source

pub fn new(val: T) -> Self

Source

pub fn with_arity(val: T, arity: Arity) -> Self

Source

pub fn with_children<N>(val: T, children: Vec<N>) -> Self
where N: Into<TreeNode<T>>,

Source

pub fn is_leaf(&self) -> bool

Source

pub fn add_child(&mut self, child: impl Into<TreeNode<T>>)

Source

pub fn attach(self, other: impl Into<TreeNode<T>>) -> Self

Source

pub fn detach(&mut self, index: usize) -> Option<TreeNode<T>>

Source

pub fn children(&self) -> Option<&[TreeNode<T>]>

Source

pub fn children_mut(&mut self) -> Option<&mut Vec<TreeNode<T>>>

Source

pub fn take_children(&mut self) -> Option<Vec<TreeNode<T>>>

Source

pub fn size(&self) -> usize

Source

pub fn height(&self) -> usize

Source

pub fn get_mut(&mut self, index: usize) -> Option<&mut TreeNode<T>>

Trait Implementations§

Source§

impl<T> AsMut<TreeNode<T>> for Tree<T>

Source§

fn as_mut(&mut self) -> &mut TreeNode<T>

Converts this type into a mutable reference of the (usually inferred) input type.
Source§

impl<T> AsRef<TreeNode<T>> for Tree<T>

Source§

fn as_ref(&self) -> &TreeNode<T>

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl<T: Clone> Clone for TreeNode<T>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug> Debug for TreeNode<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: Default> Default for TreeNode<T>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<T, V> Eval<[V], V> for TreeNode<T>
where T: Eval<[V], V>, V: Clone,

Source§

fn eval(&self, input: &[V]) -> V

Source§

impl<T, V> Eval<[V], V> for &TreeNode<T>
where T: Eval<[V], V>, V: Clone,

Implements the Eval trait for TreeNode<T> where T is Eval<[V], V>. This is where the real work is done. It recursively evaluates the TreeNode and its children until it reaches a leaf node, at which point it applies the T’s eval fn to the input.

Because a Tree has only a single root node, this can only be used to return a single value. We assume here that each leaf can eval the incoming input - this is a safe and the only real logical assumption we can make.

Source§

fn eval(&self, input: &[V]) -> V

Source§

impl<T> Factory<(usize, Option<NodeStore<T>>), Option<TreeNode<T>>> for TreeNode<T>
where T: Clone + Default,

Source§

fn new_instance( &self, (index, store): (usize, Option<NodeStore<T>>), ) -> Option<TreeNode<T>>

Source§

impl<T: Debug> Format for TreeNode<T>

Source§

fn format(&self) -> String

Source§

impl From<&'static str> for TreeNode<&'static str>

Source§

fn from(value: &'static str) -> Self

Converts to this type from the input type.
Source§

impl From<()> for TreeNode<()>

Source§

fn from(value: ()) -> Self

Converts to this type from the input type.
Source§

impl<T> From<(T, Arity)> for TreeNode<T>

Source§

fn from(value: (T, Arity)) -> Self

Converts to this type from the input type.
Source§

impl<T> From<(T, Vec<TreeNode<T>>)> for TreeNode<T>

Source§

fn from(value: (T, Vec<TreeNode<T>>)) -> Self

Converts to this type from the input type.
Source§

impl<T> From<Op<T>> for TreeNode<Op<T>>

Source§

fn from(value: Op<T>) -> Self

Converts to this type from the input type.
Source§

impl From<String> for TreeNode<String>

Source§

fn from(value: String) -> Self

Converts to this type from the input type.
Source§

impl<T> From<TreeNode<T>> for Vec<TreeNode<T>>

Source§

fn from(node: TreeNode<T>) -> Self

Converts to this type from the input type.
Source§

impl From<bool> for TreeNode<bool>

Source§

fn from(value: bool) -> Self

Converts to this type from the input type.
Source§

impl From<char> for TreeNode<char>

Source§

fn from(value: char) -> Self

Converts to this type from the input type.
Source§

impl From<f32> for TreeNode<f32>

Source§

fn from(value: f32) -> Self

Converts to this type from the input type.
Source§

impl From<f64> for TreeNode<f64>

Source§

fn from(value: f64) -> Self

Converts to this type from the input type.
Source§

impl From<i8> for TreeNode<i8>

Source§

fn from(value: i8) -> Self

Converts to this type from the input type.
Source§

impl From<i16> for TreeNode<i16>

Source§

fn from(value: i16) -> Self

Converts to this type from the input type.
Source§

impl From<i32> for TreeNode<i32>

Source§

fn from(value: i32) -> Self

Converts to this type from the input type.
Source§

impl From<i64> for TreeNode<i64>

Source§

fn from(value: i64) -> Self

Converts to this type from the input type.
Source§

impl From<i128> for TreeNode<i128>

Source§

fn from(value: i128) -> Self

Converts to this type from the input type.
Source§

impl From<isize> for TreeNode<isize>

Source§

fn from(value: isize) -> Self

Converts to this type from the input type.
Source§

impl From<u8> for TreeNode<u8>

Source§

fn from(value: u8) -> Self

Converts to this type from the input type.
Source§

impl From<u16> for TreeNode<u16>

Source§

fn from(value: u16) -> Self

Converts to this type from the input type.
Source§

impl From<u32> for TreeNode<u32>

Source§

fn from(value: u32) -> Self

Converts to this type from the input type.
Source§

impl From<u64> for TreeNode<u64>

Source§

fn from(value: u64) -> Self

Converts to this type from the input type.
Source§

impl From<u128> for TreeNode<u128>

Source§

fn from(value: u128) -> Self

Converts to this type from the input type.
Source§

impl From<usize> for TreeNode<usize>

Source§

fn from(value: usize) -> Self

Converts to this type from the input type.
Source§

impl<T> FromIterator<TreeNode<T>> for TreeChromosome<T>

Source§

fn from_iter<I: IntoIterator<Item = TreeNode<T>>>(iter: I) -> Self

Creates a value from an iterator. Read more
Source§

impl<T> Gene for TreeNode<T>
where T: Clone + PartialEq,

Source§

type Allele = T

Source§

fn allele(&self) -> &Self::Allele

Get the allele of the Gene. This is the value that the Gene represents or “expresses”.
Source§

fn allele_mut(&mut self) -> &mut Self::Allele

Get a mutable reference to the allele of the Gene.
Source§

fn new_instance(&self) -> Self

Create a new instance of the Gene.
Source§

fn with_allele(&self, allele: &Self::Allele) -> Self

Create a new Gene with the given allele.
Source§

fn set_allele(&mut self, allele: Self::Allele)

Set the allele of the Gene to the given value.
Source§

impl<T: Hash> Hash for TreeNode<T>

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<T> Node for TreeNode<T>

Source§

type Value = T

Source§

fn value(&self) -> &Self::Value

Get a reference to the node’s value.
Source§

fn value_mut(&mut self) -> &mut Self::Value

Get a mutable reference to the node’s value.
Source§

fn node_type(&self) -> NodeType

Get the NodeType of the node. As previously mentioned, if the NodeType is not supplied during creation, this value is determined by the node’s relationship to the rest of the structure holding it. IE, a GraphNode with 0 incoming connections is likely an Input, while a TreeNode with 0 children is likely a Leaf.
Source§

fn arity(&self) -> Arity

Get the arity of the node, which is the number of incoming connections it can have. In a genetic programming sense, this is the number of allowed inputs for a node. In a Graph, this is the number of allowed incoming connections while for a Tree, this is the number of children it is allowed to have.
Source§

impl<T: PartialEq> PartialEq for TreeNode<T>

Source§

fn eq(&self, other: &TreeNode<T>) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl<T: PartialEq> StructuralPartialEq for TreeNode<T>

Source§

impl<T> TreeIterator<T> for TreeNode<T>

Implement the TreeIterator trait for TreeNode

This allows for traversal of a single node and its children in pre-order, post-order, and breadth-first order.

Source§

fn iter_pre_order(&self) -> PreOrderIterator<'_, T>

Source§

fn iter_post_order(&self) -> PostOrderIterator<'_, T>

Source§

fn iter_breadth_first(&self) -> TreeBreadthFirstIterator<'_, T>

Source§

fn apply<F: Fn(&mut TreeNode<T>)>(&mut self, visit_fn: F)

Source§

impl<T> Valid for TreeNode<T>

Source§

fn is_valid(&self) -> bool

Auto Trait Implementations§

§

impl<T> Freeze for TreeNode<T>
where T: Freeze, Option<Vec<TreeNode<T>>>: Freeze,

§

impl<T> RefUnwindSafe for TreeNode<T>

§

impl<T> Send for TreeNode<T>
where T: Send, Option<Vec<TreeNode<T>>>: Send,

§

impl<T> Sync for TreeNode<T>
where T: Sync, Option<Vec<TreeNode<T>>>: Sync,

§

impl<T> Unpin for TreeNode<T>
where T: Unpin, Option<Vec<TreeNode<T>>>: Unpin,

§

impl<T> UnsafeUnpin for TreeNode<T>

§

impl<T> UnwindSafe for TreeNode<T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<I, O, T> EvalMut<I, O> for T
where T: Eval<I, O>, I: ?Sized,

Source§

fn eval_mut(&mut self, input: &I) -> O

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<N> NodeExt for N
where N: Node,

Source§

fn set_value(&mut self, value: Self::Value)

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.