tree_ds/tree/
mod.rs

1use crate::error::Error::{InvalidOperation, NodeNotFound, RootNodeAlreadyPresent};
2#[cfg(feature = "no_std")]
3use crate::lib::BTreeSet;
4use crate::lib::*;
5use crate::node::Nodes;
6use crate::prelude::{Node, Result};
7
8#[cfg(feature = "serde")]
9mod serde;
10
11/// The strategy to use when removing a node from the tree.
12///
13/// This enum represents the strategy to use when removing a node from the tree. The `RetainChildren`
14/// strategy retains the children of the node when the node is removed. The `RemoveNodeAndChildren`
15/// strategy removes the node and its children when the node is removed.
16#[derive(Clone, Debug, Copy)]
17pub enum NodeRemovalStrategy {
18	/// Retain the children of the node. This means that the children of the node are attached to the
19	/// parent of the node when the node is removed. So the children of the node become children of the
20	/// parent of the node.
21	RetainChildren,
22	/// Remove the node and all subsequent children. This means that the node and its children are
23	/// removed from the tree when the node is removed. All the subsequent grand children of the node are
24	/// removed from the tree.
25	RemoveNodeAndChildren,
26}
27
28/// The strategy to use when traversing the tree.
29///
30/// This enum represents the strategy to use when traversing the tree.
31#[allow(clippy::enum_variant_names)]
32#[derive(Clone, Debug, Copy)]
33pub enum TraversalStrategy {
34	/// Traverse the tree in pre-order. This means that the root node is visited first, then the left
35	/// child, and then the right child.
36	PreOrder,
37	/// Traverse the tree in post-order. This means that the left child is visited first, then the right
38	/// child, and then the root node.
39	PostOrder,
40	/// Traverse the tree in in-order. This means that the left child is visited first, then the root node,
41	/// and then the right child.
42	InOrder,
43}
44
45/// A subtree of a tree.
46///
47/// This struct represents a subtree of a tree. A subtree is a tree that is a part of a larger tree.
48pub type SubTree<Q, T> = Tree<Q, T>;
49
50/// A tree data structure.
51///
52/// This struct represents a tree data structure. A tree is a data structure that consists of nodes
53/// connected by edges. Each node has a parent node and zero or more child nodes. The tree has a root
54/// node that is the topmost node in the tree. The tree can be used to represent hierarchical data
55/// structures such as file systems, organization charts, and family trees. A tree can have any number
56/// of nodes and each node can have any number of children. The tree can be traversed in different
57/// orders such as pre-order, post-order, and in-order. The tree can be named for easy identification
58/// when working with multiple trees or subtrees.
59///
60/// # Type Parameters
61///
62/// * `Q` - The type of the node id.
63/// * `T` - The type of the node value.
64///
65/// # Example
66///
67/// ```rust
68/// # use tree_ds::prelude::Tree;
69///
70/// let tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
71/// ```
72#[derive(Clone, Debug, PartialEq, Eq, Hash)]
73pub struct Tree<Q, T>
74where
75	Q: PartialEq + Eq + Clone,
76	T: PartialEq + Eq + Clone,
77{
78	name: Option<String>,
79	nodes: Nodes<Q, T>,
80}
81
82impl<Q, T> Tree<Q, T>
83where
84	Q: PartialEq + Eq + Clone + Display + Hash + Ord,
85	T: PartialEq + Eq + Clone,
86{
87	/// Create a new tree.
88	///
89	/// This method creates a new tree with no nodes.
90	///
91	/// # Returns
92	///
93	/// A new tree with no nodes.
94	///
95	/// # Example
96	///
97	/// ```rust
98	/// # use tree_ds::prelude::Tree;
99	///
100	/// let tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
101	/// ```
102	pub fn new(tree_name: Option<&str>) -> Self {
103		Self {
104			name: tree_name.map(|x| x.to_string()),
105			nodes: Nodes::default(),
106		}
107	}
108
109	/// Add a node to the tree.
110	///
111	/// This method adds a node to the tree. The node is added as a child of the parent node with the
112	/// given parent id. If the parent id is `None`, the node is added as a root node. The node id is
113	/// used to identify the node and the value is the value of the node. The value can be used to store
114	/// any data that you want to associate with the node.
115	///
116	/// # Arguments
117	///
118	/// * `node_id` - The id of the node.
119	/// * `value` - The value of the node.
120	/// * `parent_id` - The id of the parent node. If `None`, the node is added as a root node.
121	///
122	/// # Returns
123	///
124	/// The id of the node that was added to the tree. However, if no parent id is provided and the tree already
125	/// has a root node, an error is returned.
126	///
127	/// # Example
128	///
129	/// ```rust
130	/// # use tree_ds::prelude::{Tree, Node};
131	///
132	/// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
133	/// let node_id = tree.add_node(Node::new(1, Some(2)), None);
134	///
135	/// assert!(node_id.is_ok());
136	/// // This should return an error because the tree already has a root node.
137	/// let another_node_id = tree.add_node(Node::new(2, Some(3)), None);
138	/// assert!(another_node_id.is_err());
139	/// ```
140	pub fn add_node(&mut self, node: Node<Q, T>, parent_id: Option<&Q>) -> Result<Q> {
141		if let Some(parent_id) = parent_id {
142			let parent = self
143				.nodes
144				.iter()
145				.find(|n| &n.get_node_id() == parent_id)
146				.ok_or(NodeNotFound(parent_id.to_string()))?;
147			parent.add_child(node.clone());
148		} else if self.get_root_node().is_some() {
149			return Err(RootNodeAlreadyPresent);
150		}
151		self.nodes.push(node.clone());
152		Ok(node.get_node_id())
153	}
154
155	/// Get the name of the tree.
156	///
157	/// This method gets the name of the tree.
158	///
159	/// # Returns
160	///
161	/// The name of the tree.
162	///
163	/// # Example
164	///
165	/// ```rust
166	/// # use tree_ds::prelude::Tree;
167	///
168	/// let tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
169	///
170	/// assert_eq!(tree.get_name(), Some("Sample Tree"));
171	/// ```
172	pub fn get_name(&self) -> Option<&str> {
173		self.name.as_deref()
174	}
175
176	/// Set the name of the tree.
177	///
178	/// This method sets the name of the tree.
179	///
180	/// # Arguments
181	///
182	/// * `name` - The name of the tree.
183	///
184	/// # Example
185	///
186	/// ```rust
187	/// # use tree_ds::prelude::Tree;
188	///
189	/// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
190	/// tree.rename(Some("New Name"));
191	/// assert_eq!(tree.get_name(), Some("New Name"));
192	/// ```
193	pub fn rename(&mut self, name: Option<&str>) {
194		self.name = name.map(|x| x.to_string());
195	}
196
197	/// Get a node in the tree.
198	///
199	/// This method gets the node with the given node id in the tree.
200	///
201	/// # Arguments
202	///
203	/// * `node_id` - The id of the node.
204	///
205	/// # Returns
206	///
207	/// The node with the given node id in the tree or `None` if the node is not found.
208	///
209	/// # Example
210	///
211	/// ```rust
212	/// # use tree_ds::prelude::{Node, Tree};
213	///
214	/// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
215	///
216	/// let node = Node::new(1, Some(2));
217	/// let node_id = tree.add_node(node.clone(), None).unwrap();
218	///
219	/// assert_eq!(tree.get_node_by_id(&node_id), Some(node));
220	/// ```
221	pub fn get_node_by_id(&self, node_id: &Q) -> Option<Node<Q, T>> {
222		self.nodes
223			.iter()
224			.find(|n| &n.get_node_id() == node_id)
225			.cloned()
226	}
227
228	/// Get the root node of the tree.
229	///
230	/// This method gets the root node of the tree. The root node is the topmost node in the tree. The
231	/// root node has no parent node.
232	///
233	/// # Returns
234	///
235	/// The root node of the tree or `None` if the tree has no root node.
236	///
237	/// # Example
238	///
239	/// ```rust
240	/// # use tree_ds::prelude::{Node, Tree};
241	///
242	/// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
243	///
244	/// let node = Node::new(1, Some(2));
245	/// tree.add_node(node.clone(), None).unwrap();
246	///
247	/// assert_eq!(tree.get_root_node(), Some(node));
248	/// ```
249	pub fn get_root_node(&self) -> Option<Node<Q, T>> {
250		self.nodes
251			.iter()
252			.find(|n| n.get_parent_id().is_none())
253			.cloned()
254	}
255
256	/// Get the height of the node.
257	///
258	/// This method gets the height of the node. The height of the node is the number of edges present
259	/// in the longest path connecting the node to a leaf node.
260	///
261	/// # Returns
262	///
263	/// The height of the node. If the node is a leaf node, the height is 0.  This method returns an
264	/// error if the node is not found in the tree.
265	///
266	/// # Example
267	///
268	/// ```rust
269	/// # use tree_ds::prelude::{Node, Tree};
270	///
271	/// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
272	///
273	/// let node_1 = tree.add_node(Node::new(1, Some(2)), None).unwrap();
274	/// let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1)).unwrap();
275	/// let node_3 = tree.add_node(Node::new(3, Some(6)), Some(&node_2)).unwrap();
276	///
277	/// assert!(tree.get_node_height(&node_2).is_ok());
278	/// assert_eq!(tree.get_node_height(&node_2).unwrap(), 1);
279	/// ```
280	pub fn get_node_height(&self, node_id: &Q) -> Result<i32> {
281		let node = self
282			.get_node_by_id(node_id)
283			.ok_or(NodeNotFound(node_id.to_string()))?;
284		let children = node.get_children_ids();
285		if children.is_empty() {
286			return Ok(0);
287		}
288		let mut height = 0;
289		for child in children {
290			let child_height = self.get_node_height(&child)?;
291			if child_height > height {
292				height = child_height;
293			}
294		}
295		Ok(height + 1)
296	}
297
298	/// Get the depth of a node in the tree.
299	///
300	/// This method gets the depth of a node in the tree. The depth of a node is the length of the path
301	/// from the root node to the node. The depth of the node is the number of edges on the path from the
302	/// root node to the node.
303	///
304	/// # Arguments
305	///
306	/// * `node_id` - The id of the node.
307	///
308	/// # Returns
309	///
310	/// The depth of the node in the tree.  This method returns an error if the node is not found in the tree.
311	///
312	/// # Example
313	///
314	/// ```rust
315	/// # use tree_ds::prelude::{Node, Tree};
316	///
317	/// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
318	///
319	/// let node_1 = tree.add_node(Node::new(1, Some(2)), None).unwrap();
320	/// let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1)).unwrap();
321	/// let node_3 = tree.add_node(Node::new(3, Some(6)), Some(&node_2)).unwrap();
322	/// let depth_result = tree.get_node_depth(&node_3);
323	/// assert!(depth_result.is_ok());
324	/// assert_eq!(depth_result.unwrap(), 2);
325	/// ```
326	pub fn get_node_depth(&self, node_id: &Q) -> Result<i32> {
327		let node = self
328			.get_node_by_id(node_id)
329			.ok_or(NodeNotFound(node_id.to_string()))?;
330		let mut depth = 0;
331		let mut parent = node.get_parent_id();
332		while let Some(parent_id) = parent {
333			depth += 1;
334			parent = self
335				.get_node_by_id(&parent_id)
336				.ok_or(NodeNotFound(parent_id.to_string()))?
337				.get_parent_id();
338		}
339		Ok(depth)
340	}
341
342	/// Get the ancestors of a node in the tree.
343	///
344	/// This method gets the ancestors of a node in the tree. The ancestors of a node are all the nodes
345	/// that are on the path from the root node to the node, not including the node itself.
346	///
347	/// # Arguments
348	///
349	/// * `node_id` - The id of the node.
350	///
351	/// # Returns
352	///
353	/// The ancestors of the node from closest to furthest.  This method returns an error if the node is not found in the tree.
354	///
355	/// # Example
356	///
357	/// ```rust
358	/// # use tree_ds::prelude::{Node, Tree};
359	///
360	/// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
361	///
362	/// let node_1 = tree.add_node(Node::new(1, Some(2)), None).unwrap();
363	/// let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1)).unwrap();
364	/// let node_3 = tree.add_node(Node::new(3, Some(6)), Some(&node_2)).unwrap();
365	/// let depth_result = tree.get_ancestor_ids(&node_3);
366	/// assert!(depth_result.is_ok());
367	/// assert_eq!(depth_result.unwrap(), vec![2, 1]);
368	/// ```
369	pub fn get_ancestor_ids(&self, node_id: &Q) -> Result<Vec<Q>> {
370		let node = self
371			.get_node_by_id(node_id)
372			.ok_or(NodeNotFound(node_id.to_string()))?;
373		let mut ancestors = vec![];
374		let mut parent = node.get_parent_id();
375		while let Some(parent_id) = parent {
376			ancestors.push(parent_id.clone());
377			parent = self
378				.get_node_by_id(&parent_id)
379				.ok_or(NodeNotFound(parent_id.to_string()))?
380				.get_parent_id();
381		}
382		Ok(ancestors)
383	}
384
385	/// Get the height of the tree.
386	///
387	/// This method gets the height of the tree. The height of the tree is the length of the longest path
388	/// from the root node to a leaf node. The height of the tree is the number of edges on the longest
389	/// path from the root node to a leaf node.
390	///
391	/// # Returns
392	///
393	/// The height of the tree. This method returns an error if the tree has no root node.
394	///
395	/// # Example
396	///
397	/// ```rust
398	/// # use tree_ds::prelude::{Node, Tree, Result};
399	///
400	/// # fn main() -> Result<()> {
401	/// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
402	///
403	/// let node_1 = tree.add_node(Node::new(1, Some(2)), None)?;
404	/// let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1))?;
405	/// let node_3 = tree.add_node(Node::new(3, Some(6)), Some(&node_2))?;
406	/// let tree_height = tree.get_height();
407	/// assert!(tree_height.is_ok());
408	/// assert_eq!(tree_height?, 2);
409	/// # Ok(())
410	/// # }
411	/// ```
412	pub fn get_height(&self) -> Result<i32> {
413		let root = self
414			.get_root_node()
415			.ok_or(InvalidOperation(String::from("Tree has no root node")))?;
416		self.get_node_height(&root.get_node_id())
417	}
418
419	/// Get the degree of a node in the tree.
420	///
421	/// This method gets the degree of a node in the tree. The degree of a node is the number of children
422	/// that the node has.
423	///
424	/// # Arguments
425	///
426	/// * `node_id` - The id of the node.
427	///
428	/// # Returns
429	///
430	/// The degree of the node in the tree. This method returns an error if the node is not found in the tree.
431	///
432	/// # Example
433	///
434	/// ```rust
435	/// # use tree_ds::prelude::{Result, Node, Tree};
436	///
437	/// # fn main() -> Result<()> {
438	/// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
439	///
440	/// let node_1 = tree.add_node(Node::new(1, Some(2)), None)?;
441	/// let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1))?;
442	/// let node_3 = tree.add_node(Node::new(3, Some(6)), Some(&node_1))?;
443	///
444	/// assert_eq!(tree.get_node_degree(&node_1)?, 2);
445	/// assert_eq!(tree.get_node_degree(&node_2)?, 0);
446	/// assert_eq!(tree.get_node_degree(&node_3)?, 0);
447	/// # Ok(())
448	/// # }
449	/// ```
450	pub fn get_node_degree(&self, node_id: &Q) -> Result<i32> {
451		let node = self
452			.get_node_by_id(node_id)
453			.ok_or(NodeNotFound(node_id.to_string()))?;
454		Ok(node.get_children_ids().len() as i32)
455	}
456
457	/// Get the nodes in the tree.
458	///
459	/// This method gets the nodes in the tree.
460	///
461	/// # Returns
462	///
463	/// The nodes in the tree.
464	///
465	/// # Example
466	///
467	/// ```rust
468	/// # use tree_ds::prelude::{Node, Tree};
469	///
470	/// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
471	///
472	/// let node = Node::new(1, Some(2));
473	/// tree.add_node(node.clone(), None).unwrap();
474	///
475	/// assert_eq!(tree.get_nodes().len(), 1);
476	/// ```
477	pub fn get_nodes(&self) -> &Nodes<Q, T> {
478		self.nodes.as_ref()
479	}
480
481	/// Remove a node from the tree.
482	///
483	/// This method removes a node from the tree. The node is removed using the given removal strategy.
484	/// The removal strategy determines how the node and its children are removed from the tree. The
485	/// `RetainChildren` strategy retains the children of the node when the node is removed. The
486	/// `RemoveNodeAndChildren` strategy removes the node and its children when the node is removed.
487	///
488	/// # Arguments
489	///
490	/// * `node_id` - The id of the node to remove.
491	/// * `strategy` - The strategy to use when removing the node.
492	///
493	/// # Returns
494	/// An error if the node is not found in the tree or if the node is the root node and the removal
495	/// strategy is `RetainChildren`.
496	///
497	/// # Example
498	///
499	/// ```rust
500	/// # use tree_ds::prelude::{Node, Tree, NodeRemovalStrategy, Result};
501	///
502	/// # fn main() -> Result<()> {
503	/// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
504	///
505	/// let node_1 = tree.add_node(Node::new(1, Some(2)), None)?;
506	/// let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1))?;
507	/// tree.add_node(Node::new(3, Some(6)), Some(&node_2))?;
508	///
509	/// tree.remove_node(&node_2, NodeRemovalStrategy::RetainChildren)?;
510	/// assert_eq!(tree.get_nodes().len(), 2);
511	/// # Ok(())
512	/// # }
513	/// ```
514	pub fn remove_node(&mut self, node_id: &Q, strategy: NodeRemovalStrategy) -> Result<()> {
515		match strategy {
516			NodeRemovalStrategy::RetainChildren => {
517				let node = self
518					.get_node_by_id(node_id)
519					.ok_or(NodeNotFound(node_id.to_string()))?;
520				let parent_node_id = &node.get_parent_id().ok_or(InvalidOperation(
521					String::from("Cannot remove root node with RetainChildren strategy"),
522				))?;
523				let parent_node = self
524					.get_node_by_id(parent_node_id)
525					.ok_or(NodeNotFound(parent_node_id.to_string()))?;
526				parent_node.remove_child(node.clone());
527				let children = node.get_children_ids();
528				for child in children {
529					if let Some(child) = self.get_node_by_id(&child) {
530						parent_node.add_child(child);
531					}
532				}
533				self.nodes.retain(|n| &n.get_node_id() != node_id);
534				Ok(())
535			}
536			NodeRemovalStrategy::RemoveNodeAndChildren => {
537				let node = self
538					.get_node_by_id(node_id)
539					.ok_or(NodeNotFound(node_id.to_string()))?;
540				let children = node.get_children_ids();
541				if let Some(parent_id) = node.get_parent_id() {
542					let parent = self
543						.get_node_by_id(&parent_id)
544						.ok_or(NodeNotFound(parent_id.to_string()))?;
545					parent.remove_child(node.clone());
546				}
547				self.nodes.retain(|n| &n.get_node_id() != node_id);
548				for child in children {
549					let child = self
550						.get_node_by_id(&child)
551						.ok_or(NodeNotFound(child.to_string()))?;
552					node.remove_child(child.clone());
553					self.remove_node(&child.get_node_id(), strategy)?;
554				}
555				Ok(())
556			}
557		}
558	}
559
560	/// Get a subsection of the tree.
561	///
562	/// This method gets a subsection of the tree starting from the node with the given node id. The
563	/// subsection is a list of nodes that are descendants of the node with the given node id upto the
564	/// given number of descendants. If the number of descendants is `None`, all the descendants of the
565	/// node are included in the subsection.
566	///
567	/// # Arguments
568	///
569	/// * `node_id` - The id of the node to get the subsection from.
570	/// * `generations` - The number of descendants to include in the subsection. If `None`, all the descendants of the node are included in the subsection.
571	///
572	/// # Returns
573	///
574	/// The subsection of the tree starting from the node with the given node id.
575	///
576	/// # Example
577	///
578	/// ```rust
579	/// # use tree_ds::prelude::{Node, Tree};
580	///
581	/// # fn main() -> tree_ds::prelude::Result<()> {
582	/// # let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
583	///
584	/// let node_1 = tree.add_node(Node::new(1, Some(2)), None)?;
585	/// let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1))?;
586	/// let node_3 = tree.add_node(Node::new(3, Some(6)), Some(&node_2))?;
587	///
588	/// let subsection = tree.get_subtree(&node_2, None)?;
589	/// assert_eq!(subsection.get_nodes().len(), 2);
590	/// # Ok(())
591	/// # }
592	/// ```
593	pub fn get_subtree(&self, node_id: &Q, generations: Option<i32>) -> Result<SubTree<Q, T>> {
594		let mut subsection = Nodes::default();
595		let node = self
596			.get_node_by_id(node_id)
597			.ok_or(NodeNotFound(node_id.to_string()))?;
598		subsection.push(node.clone());
599		// Get the subsequent children of the node recursively for the number of generations and add them to the subsection.
600		if let Some(generations) = generations {
601			let children = node.get_children_ids();
602			for current_generation in 0..generations {
603				for child in children.clone() {
604					subsection.append(
605						&mut self
606							.get_subtree(&child, Some(current_generation))?
607							.get_nodes()
608							.clone(),
609					);
610				}
611			}
612		} else {
613			let children = node.get_children_ids();
614			for child in children {
615				subsection.append(&mut self.get_subtree(&child, None)?.get_nodes().clone());
616			}
617		}
618
619		Ok(SubTree {
620			name: Some(node_id.to_string()),
621			nodes: subsection,
622		})
623	}
624
625	/// Get the siblings of a node in the tree.
626	///
627	/// This method gets the siblings of a node in the tree. The siblings of a node are the children
628	/// that share the same parent as the node.
629	///
630	/// # Arguments
631	///
632	/// * `node_id` - The id of the node to get the siblings of.
633	/// * `inclusive` - A flag that indicates whether to include the node in the siblings list.
634	///
635	/// # Returns
636	///
637	/// The siblings of the node in the tree.
638	///
639	/// # Example
640	///
641	/// ```rust
642	/// # use tree_ds::prelude::{Node, Tree};
643	///
644	/// # fn main() -> tree_ds::prelude::Result<()> {
645	/// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
646	/// let node_1 = tree.add_node(Node::new(1, Some(2)), None)?;
647	/// let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1))?;
648	/// tree.add_node(Node::new(3, Some(6)), Some(&node_1))?;
649	/// tree.add_node(Node::new(4, Some(7)), Some(&node_1))?;
650	///
651	/// let siblings = tree.get_sibling_ids(&node_2, false)?;
652	/// assert_eq!(siblings.len(), 2);
653	///
654	/// let siblings = tree.get_sibling_ids(&node_2, true)?;
655	/// assert_eq!(siblings.len(), 3);
656	/// # Ok(())
657	/// # }
658	/// ```
659	pub fn get_sibling_ids(&self, node_id: &Q, inclusive: bool) -> Result<Vec<Q>> {
660		let node = self
661			.get_node_by_id(node_id)
662			.ok_or(NodeNotFound(node_id.to_string()))?;
663		if let Some(parent_id) = node.get_parent_id() {
664			let parent = self
665				.get_node_by_id(&parent_id)
666				.ok_or(NodeNotFound(parent_id.to_string()))?;
667			if inclusive {
668				Ok(parent.get_children_ids().clone())
669			} else {
670				Ok(parent
671					.get_children_ids()
672					.iter()
673					.filter(|x| *x != node_id)
674					.cloned()
675					.collect())
676			}
677		} else if inclusive {
678			// We need to clone this since Q does not implement Copy.
679			Ok(vec![node_id.clone()])
680		} else {
681			Ok(vec![])
682		}
683	}
684
685	/// Add a subsection to the tree.
686	///
687	/// This method adds a subsection to the tree. The subsection is a list of nodes that are descendants
688	/// of the node with the given node id. The subsection is added as children of the node with the
689	/// given node id.
690	///
691	/// # Arguments
692	///
693	/// * `node_id` - The id of the node to add the subsection to.
694	/// * `subtree` - The subsection to add to the tree.
695	///
696	/// # Returns
697	/// This function return an error if:
698	/// - The node is not found in the tree.
699	/// - The subsection has no root node.
700	///
701	/// # Example
702	///
703	/// ```rust
704	/// # use tree_ds::prelude::{Node, Tree, SubTree};
705	///
706	/// # fn main() -> tree_ds::prelude::Result<()> {
707	/// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
708	/// let node_id = tree.add_node(Node::new(1, Some(2)), None)?;
709	/// let mut subtree = SubTree::new(Some("Sample Tree"));
710	/// let node_2 = subtree.add_node(Node::new(2, Some(3)), None)?;
711	/// subtree.add_node(Node::new(3, Some(6)), Some(&node_2))?;
712	/// tree.add_subtree(&node_id, subtree)?;
713	/// assert_eq!(tree.get_nodes().len(), 3);
714	/// # Ok(())
715	/// # }
716	/// ```
717	pub fn add_subtree(&mut self, node_id: &Q, subtree: SubTree<Q, T>) -> Result<()> {
718		let node = self
719			.get_node_by_id(node_id)
720			.ok_or(NodeNotFound(node_id.to_string()))?;
721		// Get the root node in the subsection and add it as a child of the node.
722		let subtree_nodes = subtree.get_nodes();
723		let root_node = subtree
724			.get_root_node()
725			.ok_or(InvalidOperation(String::from("Subtree has no root node.")))?;
726		node.add_child(root_node.clone());
727		self.nodes.append(&mut subtree_nodes.clone());
728		Ok(())
729	}
730
731	/// Traverse the subtree from the given node.
732	///
733	/// This method traverses the subtree from the given node in the given order.
734	///
735	/// # Arguments
736	///
737	/// * `order` - The order to traverse the tree.
738	/// * `node_id` - The id of the node to start the traversal from.
739	///
740	/// # Returns
741	///
742	/// The nodes in the tree in the given order. This method returns an error if the node is not found
743	/// in the tree.
744	///
745	/// # Example
746	///
747	/// ```rust
748	/// # use tree_ds::prelude::{Node, Tree, TraversalStrategy};
749	///
750	/// # fn main() -> tree_ds::prelude::Result<()> {
751	/// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
752	/// let node_1 = tree.add_node(Node::new(1, Some(2)), None)?;
753	/// let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1))?;
754	/// let node_3 = tree.add_node(Node::new(3, Some(6)), Some(&node_2))?;
755	///
756	/// let ordered_nodes = tree.traverse(&node_1, TraversalStrategy::PreOrder)?;
757	/// # let expected = vec![1, 2, 3];
758	/// # assert_eq!(ordered_nodes, expected);
759	/// # Ok(())
760	/// # }
761	/// ```
762	pub fn traverse(&self, node_id: &Q, order: TraversalStrategy) -> Result<Vec<Q>> {
763		let mut nodes = vec![];
764		let node = self
765			.get_node_by_id(node_id)
766			.ok_or(NodeNotFound(node_id.to_string()))?;
767		match &order {
768			TraversalStrategy::PreOrder => {
769				nodes.push(node_id.clone());
770				for child_id in node.get_children_ids().iter() {
771					nodes.append(&mut self.traverse(child_id, order)?);
772				}
773			}
774			TraversalStrategy::PostOrder => {
775				for child_id in node.get_children_ids().iter() {
776					nodes.append(&mut self.traverse(child_id, order)?);
777				}
778				nodes.push(node_id.clone());
779			}
780			TraversalStrategy::InOrder => {
781				for (index, child_id) in node.get_children_ids().iter().enumerate() {
782					if index == 0 {
783						nodes.append(&mut self.traverse(child_id, order)?);
784						if !nodes.contains(child_id) {
785							nodes.push(child_id.clone());
786						}
787						if !nodes.contains(node_id) {
788							nodes.push(node_id.clone());
789						}
790					} else {
791						nodes.push(child_id.clone());
792						nodes.append(&mut self.traverse(child_id, order)?);
793					}
794				}
795			}
796		}
797		#[cfg(not(feature = "no_std"))]
798		let mut seen = HashSet::new();
799		#[cfg(feature = "no_std")]
800		let mut seen = BTreeSet::new();
801		nodes.retain(|x| seen.insert(x.clone()));
802		Ok(nodes)
803	}
804
805	/// Print the tree.
806	///
807	/// This method prints the tree to the standard output.
808	#[doc(hidden)]
809	fn print_tree(
810		tree: &Tree<Q, T>,
811		f: &mut Formatter<'_>,
812	) -> Result<()>
813	where
814		Q: PartialEq + Eq + Clone + Display + Hash,
815		T: PartialEq + Eq + Clone + Display + Default,
816	{
817		Tree::print_sub_tree(tree, f, &tree.get_root_node().ok_or(FmtError)?, String::new(), true)?;
818		Ok(())
819	}
820
821	fn print_sub_tree(tree: &Tree<Q, T>,
822					  f: &mut Formatter<'_>,
823					  root_node: &Node<Q, T>,
824					  mut parent_prefix: String,
825					  is_last_child: bool,
826	) -> Result<()>
827	where
828		Q: PartialEq + Eq + Clone + Display + Hash,
829		T: PartialEq + Eq + Clone + Display + Default,
830	{
831		write!(f, "{}", parent_prefix)?;
832		if is_last_child {
833			if tree.get_root_node().is_some_and(|x| x.get_node_id() == root_node.get_node_id()) {
834				writeln!(f, "{}", root_node)?;
835			} else {
836				writeln!(f, "└── {}", root_node)?;
837				parent_prefix = format!("{}    ", parent_prefix);
838			}
839		} else {
840			writeln!(f, "├── {}", root_node)?;
841			parent_prefix = format!("{}│   ", parent_prefix);
842		}
843		let children = root_node.get_children_ids();
844		for (index, node_id) in children.iter().enumerate() {
845			let node = tree
846				.get_node_by_id(node_id)
847				.ok_or(NodeNotFound(node_id.to_string()))?;
848
849			Tree::print_sub_tree(tree, f, &node, parent_prefix.clone(), index == children.len() - 1)?;
850		}
851		Ok(())
852	}
853}
854
855impl<Q, T> Default for Tree<Q, T>
856where
857	Q: PartialEq + Eq + Clone,
858	T: PartialEq + Eq + Clone,
859{
860	/// Create a new tree with no nodes.
861	fn default() -> Self {
862		Tree {
863			name: None,
864			nodes: Nodes::default(),
865		}
866	}
867}
868
869impl<Q, T> Display for Tree<Q, T>
870where
871	Q: PartialEq + Eq + Clone + Display + Hash + Ord,
872	T: PartialEq + Eq + Clone + Display + Default,
873{
874	/// Print the tree.
875	fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
876		if let Some(name) = &self.name {
877			writeln!(f, "{}", name)?;
878			writeln!(
879				f,
880				"{}",
881				name.clone().chars().map(|_| "*").collect::<String>()
882			)?;
883		}
884		Tree::print_tree(self, f).map_err(|_| FmtError)?;
885		Ok(())
886	}
887}
888
889impl<Q, T> Drop for Tree<Q, T>
890where
891	Q: PartialEq + Eq + Clone,
892	T: PartialEq + Eq + Clone,
893{
894	/// Drop the tree.
895	#[doc(hidden)]
896	fn drop(&mut self) {
897		self.nodes.clear();
898	}
899}
900
901#[cfg(test)]
902mod tests {
903	#[allow(deprecated)]
904	#[cfg(feature = "no_std")]
905	use core::hash::SipHasher as DefaultHasher;
906	#[cfg(not(feature = "no_std"))]
907	use std::hash::DefaultHasher;
908
909	use crate::lib::*;
910
911	use super::*;
912
913	#[test]
914	fn test_tree_new() {
915		let tree = Tree::<u32, u32>::new(Some("Sample Tree"));
916		assert_eq!(tree.nodes.len(), 0);
917	}
918
919	#[test]
920	fn test_tree_add_node() {
921		let mut tree = Tree::new(Some("Sample Tree"));
922		let node_id = tree.add_node(Node::new(1, Some(2)), None).unwrap();
923		assert_eq!(tree.nodes.len(), 1);
924		assert_eq!(node_id, 1);
925		let node_id_2 = tree.add_node(Node::new(2, Some(3)), Some(&1)).unwrap();
926		assert_eq!(tree.nodes.len(), 2);
927		assert_eq!(node_id_2, 2);
928		let node_2 = tree.get_node_by_id(&2).unwrap();
929		assert_eq!(node_2.get_parent_id().unwrap(), 1);
930	}
931
932	#[test]
933	fn test_tree_add_more_than_one_root_node() {
934		let mut tree = Tree::new(Some("Sample Tree"));
935		let result = tree.add_node(Node::new(1, Some(2)), None);
936		assert!(result.is_ok());
937		let node_id = result.unwrap();
938		assert_eq!(tree.nodes.len(), 1);
939		assert_eq!(node_id, 1);
940		let result = tree.add_node(Node::new(2, Some(3)), None);
941		assert!(result.is_err());
942		assert_eq!(result.unwrap_err(), RootNodeAlreadyPresent);
943	}
944
945	#[test]
946	fn test_tree_get_node() {
947		let mut tree = Tree::new(Some("Sample Tree"));
948		let node = Node::new(1, Some(2));
949		tree.add_node(node.clone(), None).unwrap();
950		assert_eq!(tree.get_node_by_id(&1), Some(node));
951		assert_eq!(tree.get_node_by_id(&2), None);
952	}
953
954	#[test]
955	fn test_tree_get_no_existent_node() {
956		let tree = Tree::<u32, u32>::new(Some("Sample Tree"));
957		assert_eq!(tree.get_node_by_id(&1), None);
958	}
959
960	#[test]
961	fn test_tree_get_nodes() {
962		let mut tree = Tree::new(Some("Sample Tree"));
963		let node1 = Node::new(1, Some(2));
964		let node2 = Node::new(2, Some(4));
965		let node3 = Node::new(3, Some(7));
966		let node1_id = tree.add_node(node1.clone(), None).unwrap();
967		let node2_id = tree.add_node(node2.clone(), Some(&node1_id)).unwrap();
968		let _ = tree.add_node(node3.clone(), Some(&node2_id)).unwrap();
969		assert_eq!(tree.get_nodes().len(), 3);
970	}
971
972	#[test]
973	fn test_tree_get_root_node() {
974		let mut tree = Tree::new(Some("Sample Tree"));
975		let node = Node::new(1, Some(2));
976		tree.add_node(node.clone(), None).unwrap();
977		assert_eq!(tree.get_root_node(), Some(node));
978	}
979
980	#[test]
981	fn test_tree_get_node_height() {
982		let mut tree = Tree::new(Some("Sample Tree"));
983		let node_1 = tree.add_node(Node::new(1, Some(2)), None).unwrap();
984		let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1)).unwrap();
985		let node_3 = tree.add_node(Node::new(3, Some(6)), Some(&node_2)).unwrap();
986		assert_eq!(tree.get_node_height(&node_1).unwrap(), 2);
987		assert_eq!(tree.get_node_height(&node_2).unwrap(), 1);
988		assert_eq!(tree.get_node_height(&node_3).unwrap(), 0);
989	}
990
991	#[test]
992	fn test_tree_get_node_height_no_existent_node() {
993		let tree = Tree::<u32, u32>::new(Some("Sample Tree"));
994		let result = tree.get_node_height(&1);
995		assert!(result.is_err());
996		assert_eq!(result.unwrap_err(), NodeNotFound("1".to_string()));
997	}
998
999	#[test]
1000	fn test_tree_get_node_depth() {
1001		let mut tree = Tree::new(Some("Sample Tree"));
1002		let node_1 = tree.add_node(Node::new(1, Some(2)), None).unwrap();
1003		let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1)).unwrap();
1004		let node_3 = tree.add_node(Node::new(3, Some(6)), Some(&node_2)).unwrap();
1005		assert_eq!(tree.get_node_depth(&node_3).unwrap(), 2);
1006		assert_eq!(tree.get_node_depth(&node_2).unwrap(), 1);
1007		assert_eq!(tree.get_node_depth(&node_1).unwrap(), 0);
1008	}
1009
1010	#[test]
1011	fn test_tree_get_ancestor_ids() {
1012		let mut tree = Tree::new(Some("Sample Tree"));
1013		let node_1 = tree.add_node(Node::new(1, Some(2)), None).unwrap();
1014		let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1)).unwrap();
1015		let node_3 = tree.add_node(Node::new(3, Some(6)), Some(&node_2)).unwrap();
1016		let node_4 = tree.add_node(Node::new(4, Some(5)), Some(&node_2)).unwrap();
1017		assert_eq!(tree.get_ancestor_ids(&node_4).unwrap(), vec![2, 1]);
1018		assert_eq!(tree.get_ancestor_ids(&node_3).unwrap(), vec![2, 1]);
1019		assert_eq!(tree.get_ancestor_ids(&node_2).unwrap(), vec![1]);
1020		assert_eq!(tree.get_ancestor_ids(&node_1).unwrap(), Vec::<i32>::new());
1021	}
1022
1023	#[test]
1024	fn test_tree_get_node_ancestor_ids_no_existent_node() {
1025		let tree = Tree::<u32, u32>::new(Some("Sample Tree"));
1026		let result = tree.get_ancestor_ids(&1);
1027		assert!(result.is_err());
1028		assert_eq!(result.unwrap_err(), NodeNotFound("1".to_string()));
1029	}
1030
1031	#[test]
1032	fn test_tree_get_node_depth_no_existent_node() {
1033		let tree = Tree::<u32, u32>::new(Some("Sample Tree"));
1034		let result = tree.get_node_depth(&1);
1035		assert!(result.is_err());
1036		assert_eq!(result.unwrap_err(), NodeNotFound("1".to_string()));
1037	}
1038
1039	#[test]
1040	fn test_tree_get_height() {
1041		let mut tree = Tree::new(Some("Sample Tree"));
1042		let node_1 = tree.add_node(Node::new(1, Some(2)), None).unwrap();
1043		let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1)).unwrap();
1044		tree.add_node(Node::new(3, Some(6)), Some(&node_2)).unwrap();
1045		assert_eq!(tree.get_height().unwrap(), 2);
1046	}
1047
1048	#[test]
1049	fn test_tree_get_height_no_root_node() {
1050		let tree = Tree::<u32, u32>::new(Some("Sample Tree"));
1051		let result = tree.get_height();
1052		assert!(result.is_err());
1053		assert_eq!(
1054			result.unwrap_err(),
1055			InvalidOperation("Tree has no root node".to_string())
1056		);
1057	}
1058
1059	#[test]
1060	fn test_tree_get_node_degree() {
1061		let mut tree = Tree::new(Some("Sample Tree"));
1062		let node_1 = tree.add_node(Node::new(1, Some(2)), None).unwrap();
1063		let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1)).unwrap();
1064		let node_3 = tree.add_node(Node::new(3, Some(6)), Some(&node_1)).unwrap();
1065		assert_eq!(tree.get_node_degree(&node_1).unwrap(), 2);
1066		assert_eq!(tree.get_node_degree(&node_2).unwrap(), 0);
1067		assert_eq!(tree.get_node_degree(&node_3).unwrap(), 0);
1068	}
1069
1070	#[test]
1071	fn test_tree_get_node_degree_no_existent_node() {
1072		let tree = Tree::<u32, u32>::new(Some("Sample Tree"));
1073		let result = tree.get_node_degree(&1);
1074		assert!(result.is_err());
1075		assert_eq!(result.unwrap_err(), NodeNotFound("1".to_string()));
1076	}
1077
1078	#[test]
1079	fn test_tree_remove_node() -> crate::prelude::Result<()> {
1080		let mut tree = Tree::new(Some("Sample Tree"));
1081		let node = Node::new(1, Some(2));
1082		tree.add_node(node.clone(), None)?;
1083		let node_2 = Node::new(2, Some(3));
1084		tree.add_node(node_2.clone(), Some(&1))?;
1085		let node_3 = Node::new(3, Some(6));
1086		tree.add_node(node_3.clone(), Some(&2))?;
1087		tree.remove_node(&2, NodeRemovalStrategy::RetainChildren)?;
1088		assert_eq!(tree.get_nodes().len(), 2);
1089		let node_4 = Node::new(4, Some(5));
1090		let node_5 = Node::new(5, Some(12));
1091		tree.add_node(node_4.clone(), Some(&3))?;
1092		tree.add_node(node_5.clone(), Some(&3))?;
1093		tree.remove_node(&3, NodeRemovalStrategy::RemoveNodeAndChildren)?;
1094		assert_eq!(tree.get_nodes().len(), 1);
1095		Ok(())
1096	}
1097
1098	#[test]
1099	fn test_tree_remove_node_no_existent_node() {
1100		let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
1101		let result = tree.remove_node(&1, NodeRemovalStrategy::RetainChildren);
1102		assert!(result.is_err());
1103		assert_eq!(result.unwrap_err(), NodeNotFound("1".to_string()));
1104	}
1105
1106	#[test]
1107	fn test_tree_remove_node_no_root_node() {
1108		let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
1109		tree.add_node(Node::new(1, Some(2)), None).unwrap();
1110		let result = tree.remove_node(&1, NodeRemovalStrategy::RetainChildren);
1111		assert!(result.is_err());
1112		assert_eq!(
1113			result.unwrap_err(),
1114			InvalidOperation("Cannot remove root node with RetainChildren strategy".to_string())
1115		);
1116	}
1117
1118	#[test]
1119	fn test_tree_get_subsection() {
1120		let mut tree = Tree::new(Some("Sample Tree"));
1121		let node = Node::new(1, Some(2));
1122		tree.add_node(node.clone(), None).unwrap();
1123		let node_2 = Node::new(2, Some(3));
1124		tree.add_node(node_2.clone(), Some(&1)).unwrap();
1125		let node_3 = Node::new(3, Some(6));
1126		tree.add_node(node_3.clone(), Some(&2)).unwrap();
1127		let node_4 = Node::new(4, Some(5));
1128		tree.add_node(node_4.clone(), Some(&2)).unwrap();
1129		let node_5 = Node::new(5, Some(6));
1130		tree.add_node(node_5.clone(), Some(&3)).unwrap();
1131		let subsection = tree.get_subtree(&2, None).unwrap();
1132		assert_eq!(subsection.get_name(), Some("2"));
1133		assert_eq!(subsection.get_nodes().len(), 4);
1134		let subsection = tree.get_subtree(&2, Some(0)).unwrap();
1135		assert_eq!(subsection.get_nodes().len(), 1);
1136		let subsection = tree.get_subtree(&2, Some(1)).unwrap();
1137		assert_eq!(subsection.get_nodes().len(), 3);
1138	}
1139
1140	#[test]
1141	fn test_tree_get_subsection_no_existent_node() {
1142		let tree = Tree::<u32, u32>::new(Some("Sample Tree"));
1143		let result = tree.get_subtree(&1, None);
1144		assert!(result.is_err());
1145		assert_eq!(result.unwrap_err(), NodeNotFound("1".to_string()));
1146	}
1147
1148	#[test]
1149	fn get_siblings() {
1150		let mut tree = Tree::new(Some("Sample Tree"));
1151		let node_1 = tree.add_node(Node::new(1, Some(2)), None).unwrap();
1152		let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1)).unwrap();
1153		tree.add_node(Node::new(3, Some(6)), Some(&node_1)).unwrap();
1154		tree.add_node(Node::new(4, Some(7)), Some(&node_1)).unwrap();
1155		let siblings = tree.get_sibling_ids(&node_2, false).unwrap();
1156		assert_eq!(siblings.len(), 2);
1157		let siblings = tree.get_sibling_ids(&node_2, true).unwrap();
1158		assert_eq!(siblings.len(), 3);
1159	}
1160
1161	#[test]
1162	fn test_tree_get_siblings_no_existent_node() {
1163		let tree = Tree::<u32, u32>::new(Some("Sample Tree"));
1164		let result = tree.get_sibling_ids(&1, false);
1165		assert!(result.is_err());
1166		assert_eq!(result.unwrap_err(), NodeNotFound("1".to_string()));
1167	}
1168
1169	#[test]
1170	fn test_tree_add_subsection() {
1171		let mut tree = Tree::new(Some("Sample Tree"));
1172		let node_id = tree.add_node(Node::new(1, Some(2)), None).unwrap();
1173		let mut subtree = SubTree::new(Some("Sample Tree"));
1174		let node_2 = subtree.add_node(Node::new(2, Some(3)), None).unwrap();
1175		subtree
1176			.add_node(Node::new(3, Some(6)), Some(&node_2))
1177			.unwrap();
1178		tree.add_subtree(&node_id, subtree).unwrap();
1179		assert_eq!(tree.get_nodes().len(), 3);
1180	}
1181
1182	#[test]
1183	fn test_tree_add_subsection_no_attaching_node() {
1184		let mut tree = Tree::new(Some("Sample Tree"));
1185		let mut subtree = SubTree::new(Some("Sample Tree"));
1186		let node_2 = subtree.add_node(Node::new(2, Some(3)), None).unwrap();
1187		subtree
1188			.add_node(Node::new(3, Some(6)), Some(&node_2))
1189			.unwrap();
1190		let result = tree.add_subtree(&1, subtree);
1191		assert!(result.is_err());
1192		assert_eq!(result.unwrap_err(), NodeNotFound("1".to_string()));
1193	}
1194
1195	#[test]
1196	fn test_tree_add_subsection_with_no_root_node() {
1197		let mut tree = Tree::new(Some("Sample Tree"));
1198		let node_id = tree.add_node(Node::new(1, Some(2)), None).unwrap();
1199		let mut subtree = SubTree::new(Some("Sample Tree"));
1200		let node_2 = Node::new(2, Some(3));
1201		let result = subtree.add_node(Node::new(3, Some(3)), Some(&node_2.get_node_id()));
1202		assert!(result.is_err());
1203		assert_eq!(result.unwrap_err(), NodeNotFound("2".to_string()));
1204		let result = tree.add_subtree(&node_id, subtree);
1205		assert!(result.is_err());
1206		assert_eq!(
1207			result.unwrap_err(),
1208			InvalidOperation("Subtree has no root node.".to_string())
1209		);
1210	}
1211
1212	#[test]
1213	fn test_tree_display() {
1214		let mut tree = Tree::new(Some("Sample Tree"));
1215		let node_1 = tree.add_node(Node::new(1, Some(2)), None).unwrap();
1216		let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1)).unwrap();
1217		let node_3 = tree.add_node(Node::new(3, Some(6)), Some(&node_2)).unwrap();
1218		tree.add_node(Node::new(4, Some(5)), Some(&node_2)).unwrap();
1219		tree.add_node(Node::new(5, Some(6)), Some(&node_3)).unwrap();
1220		#[cfg(feature = "print_node_id")]
1221		let expected_str = "Sample Tree\n***********\n1: 2\n└── 2: 3\n    ├── 3: 6\n    │   └── 5: 6\n    └── 4: 5\n";
1222		#[cfg(not(feature = "print_node_id"))]
1223		let expected_str =
1224			"Sample Tree\n***********\n2\n└── 3\n    ├── 6\n    │   └── 6\n    └── 5\n";
1225
1226		assert_eq!(tree.to_string(), expected_str);
1227	}
1228
1229	#[test]
1230	fn compare_tree() {
1231		let mut tree = Tree::new(Some("Sample Tree"));
1232		let node_1 = tree.add_node(Node::new(1, Some(2)), None).unwrap();
1233		let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1)).unwrap();
1234		let node_3 = tree.add_node(Node::new(3, Some(6)), Some(&node_2)).unwrap();
1235		tree.add_node(Node::new(4, Some(5)), Some(&node_2)).unwrap();
1236		tree.add_node(Node::new(5, Some(6)), Some(&node_3)).unwrap();
1237		let mut tree_2 = Tree::new(Some("Sample Tree"));
1238		let node_1 = tree_2.add_node(Node::new(1, Some(2)), None).unwrap();
1239		let node_2 = tree_2
1240			.add_node(Node::new(2, Some(3)), Some(&node_1))
1241			.unwrap();
1242		let node_3 = tree_2
1243			.add_node(Node::new(3, Some(6)), Some(&node_2))
1244			.unwrap();
1245		tree_2
1246			.add_node(Node::new(4, Some(5)), Some(&node_2))
1247			.unwrap();
1248		tree_2
1249			.add_node(Node::new(5, Some(6)), Some(&node_3))
1250			.unwrap();
1251		assert_eq!(tree, tree_2);
1252		let tree_3 = Tree::new(Some("Sample Tree"));
1253		assert_ne!(tree, tree_3);
1254	}
1255
1256	#[test]
1257	fn test_tree_traverse() {
1258		let mut tree = Tree::new(Some("Sample Tree"));
1259		let node_1 = tree.add_node(Node::new(1, Some(2)), None).unwrap();
1260		let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1)).unwrap();
1261		let node_3 = tree.add_node(Node::new(3, Some(6)), Some(&node_1)).unwrap();
1262		let node_4 = tree.add_node(Node::new(4, Some(5)), Some(&node_2)).unwrap();
1263		let node_5 = tree.add_node(Node::new(5, Some(6)), Some(&node_2)).unwrap();
1264		let node_6 = tree.add_node(Node::new(6, Some(7)), Some(&node_3)).unwrap();
1265		let preorder_nodes = tree.traverse(&node_1, TraversalStrategy::PreOrder).unwrap();
1266		let expected_preorder = vec![node_1, node_2, node_4, node_5, node_3, node_6];
1267		assert_eq!(preorder_nodes, expected_preorder);
1268
1269		let in_order_nodes = tree.traverse(&node_1, TraversalStrategy::InOrder).unwrap();
1270		let expected_in_order = vec![node_4, node_2, node_5, node_1, node_3, node_6];
1271		assert_eq!(in_order_nodes, expected_in_order);
1272
1273		let post_order_nodes = tree
1274			.traverse(&node_1, TraversalStrategy::PostOrder)
1275			.unwrap();
1276		let expected_post_order = vec![node_4, node_5, node_2, node_6, node_3, node_1];
1277		assert_eq!(post_order_nodes, expected_post_order);
1278	}
1279
1280	#[allow(deprecated)] // This is solely for testing hashing in no_std.
1281	#[test]
1282	fn test_hashing() {
1283		let mut tree = Tree::new(Some("Sample Tree"));
1284		let node_1 = tree.add_node(Node::new(1, Some(2)), None).unwrap();
1285		let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1)).unwrap();
1286		let node_3 = tree.add_node(Node::new(3, Some(6)), Some(&node_2)).unwrap();
1287		tree.add_node(Node::new(4, Some(5)), Some(&node_2)).unwrap();
1288		tree.add_node(Node::new(5, Some(6)), Some(&node_3)).unwrap();
1289		let mut tree_2 = Tree::new(Some("Sample Tree"));
1290		let node_1 = tree_2.add_node(Node::new(1, Some(2)), None).unwrap();
1291		let node_2 = tree_2
1292			.add_node(Node::new(2, Some(3)), Some(&node_1))
1293			.unwrap();
1294		let node_3 = tree_2
1295			.add_node(Node::new(3, Some(6)), Some(&node_2))
1296			.unwrap();
1297		tree_2
1298			.add_node(Node::new(4, Some(5)), Some(&node_2))
1299			.unwrap();
1300		tree_2
1301			.add_node(Node::new(5, Some(6)), Some(&node_3))
1302			.unwrap();
1303		assert_eq!(tree, tree_2);
1304		let mut hasher = DefaultHasher::new();
1305		tree.hash(&mut hasher);
1306		let tree_hash = hasher.finish();
1307		let mut hasher = DefaultHasher::new();
1308		tree_2.hash(&mut hasher);
1309		let tree_2_hash = hasher.finish();
1310		assert_eq!(tree_hash, tree_2_hash);
1311	}
1312
1313	#[test]
1314	fn test_sort_children_by_height() {
1315		let mut tree = Tree::new(Some("Sample Tree"));
1316		let node_1 = tree.add_node(Node::new(1, Some(1)), None).unwrap();
1317		let _node_2 = tree.add_node(Node::new(2, Some(2)), Some(&node_1)).unwrap();
1318		let node_3 = tree.add_node(Node::new(3, Some(3)), Some(&node_1)).unwrap();
1319		let node_4 = tree.add_node(Node::new(4, Some(4)), Some(&node_3)).unwrap();
1320		let _node_5 = tree.add_node(Node::new(5, Some(5)), Some(&node_4)).unwrap();
1321
1322		let root = tree.get_node_by_id(&node_1).unwrap();
1323		root.sort_children(|a, b| {
1324			let a_height = tree.get_node_height(a).unwrap();
1325			let b_height = tree.get_node_height(b).unwrap();
1326			a_height.cmp(&b_height).reverse()
1327		});
1328
1329		assert_eq!(
1330			tree.get_node_by_id(&node_1).unwrap().get_children_ids(),
1331			vec![3, 2]
1332		);
1333	}
1334}