tree_ds/tree/
sync_tree.rs

1use crate::error::Error::{InvalidOperation, NodeNotFound, RootNodeAlreadyPresent};
2use crate::lib::*;
3use crate::node::{Node, Nodes};
4use crate::prelude::{NodeRemovalStrategy, SubTree, TraversalStrategy};
5#[cfg(feature = "serde")]
6use ::serde::{ser::SerializeStruct, Deserialize, Serialize};
7
8/// A tree data structure.
9///
10/// This struct represents a tree data structure. A tree is a data structure that consists of nodes
11/// connected by edges. Each node has a parent node and zero or more child nodes. The tree has a root
12/// node that is the topmost node in the tree. The tree can be used to represent hierarchical data
13/// structures such as file systems, organization charts, and family trees. A tree can have any number
14/// of nodes and each node can have any number of children. The tree can be traversed in different
15/// orders such as pre-order, post-order, and in-order. The tree can be named for easy identification
16/// when working with multiple trees or subtrees.
17///
18/// # Type Parameters
19///
20/// * `Q` - The type of the node id.
21/// * `T` - The type of the node value.
22///
23/// # Example
24///
25/// ```rust
26/// # use tree_ds::prelude::Tree;
27///
28/// let tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
29/// ```
30#[derive(Clone, Debug, PartialEq, Eq, Hash)]
31pub struct Tree<Q, T>
32where
33    Q: PartialEq + Eq + Clone,
34    T: PartialEq + Eq + Clone,
35{
36    name: Option<String>,
37    nodes: Nodes<Q, T>,
38}
39
40impl<Q, T> Tree<Q, T>
41where
42    Q: PartialEq + Eq + Clone + Display + Hash + Ord,
43    T: PartialEq + Eq + Clone,
44{
45    /// Create a new tree.
46    ///
47    /// This method creates a new tree with no nodes.
48    ///
49    /// # Returns
50    ///
51    /// A new tree with no nodes.
52    ///
53    /// # Example
54    ///
55    /// ```rust
56    /// # use tree_ds::prelude::Tree;
57    ///
58    /// let tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
59    /// ```
60    pub fn new(tree_name: Option<&str>) -> Self {
61        Self {
62            name: tree_name.map(|x| x.to_string()),
63            nodes: Nodes::default(),
64        }
65    }
66
67    /// Add a node to the tree.
68    ///
69    /// This method adds a node to the tree. The node is added as a child of the parent node with the
70    /// given parent id. If the parent id is `None`, the node is added as a root node. The node id is
71    /// used to identify the node and the value is the value of the node. The value can be used to store
72    /// any data that you want to associate with the node.
73    ///
74    /// # Arguments
75    ///
76    /// * `node_id` - The id of the node.
77    /// * `value` - The value of the node.
78    /// * `parent_id` - The id of the parent node. If `None`, the node is added as a root node.
79    ///
80    /// # Returns
81    ///
82    /// The id of the node that was added to the tree. However, if no parent id is provided and the tree already
83    /// has a root node, an error is returned.
84    ///
85    /// # Example
86    ///
87    /// ```rust
88    /// # use tree_ds::prelude::{Tree, Node};
89    ///
90    /// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
91    /// let node_id = tree.add_node(Node::new(1, Some(2)), None);
92    ///
93    /// assert!(node_id.is_ok());
94    /// // This should return an error because the tree already has a root node.
95    /// let another_node_id = tree.add_node(Node::new(2, Some(3)), None);
96    /// assert!(another_node_id.is_err());
97    /// ```
98    pub fn add_node(
99        &mut self,
100        node: Node<Q, T>,
101        parent_id: Option<&Q>,
102    ) -> crate::prelude::Result<Q> {
103        if let Some(parent_id) = parent_id {
104            let parent = self
105                .nodes
106                .iter()
107                .find(|n| &n.get_node_id().expect("Error: Failed to get the node Id.") == parent_id)
108                .ok_or(NodeNotFound(parent_id.to_string()))?;
109            parent.add_child(node.clone())?;
110        } else if self.get_root_node().is_some() {
111            return Err(RootNodeAlreadyPresent);
112        }
113        self.nodes.push(node.clone());
114        node.get_node_id()
115    }
116
117    /// Get the name of the tree.
118    ///
119    /// This method gets the name of the tree.
120    ///
121    /// # Returns
122    ///
123    /// The name of the tree.
124    ///
125    /// # Example
126    ///
127    /// ```rust
128    /// # use tree_ds::prelude::Tree;
129    ///
130    /// let tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
131    ///
132    /// assert_eq!(tree.get_name(), Some("Sample Tree"));
133    /// ```
134    pub fn get_name(&self) -> Option<&str> {
135        self.name.as_deref()
136    }
137
138    /// Set the name of the tree.
139    ///
140    /// This method sets the name of the tree.
141    ///
142    /// # Arguments
143    ///
144    /// * `name` - The name of the tree.
145    ///
146    /// # Example
147    ///
148    /// ```rust
149    /// # use tree_ds::prelude::Tree;
150    ///
151    /// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
152    /// tree.rename(Some("New Name"));
153    /// assert_eq!(tree.get_name(), Some("New Name"));
154    /// ```
155    pub fn rename(&mut self, name: Option<&str>) {
156        self.name = name.map(|x| x.to_string());
157    }
158
159    /// Get a node in the tree.
160    ///
161    /// This method gets the node with the given node id in the tree.
162    ///
163    /// # Arguments
164    ///
165    /// * `node_id` - The id of the node.
166    ///
167    /// # Returns
168    ///
169    /// The node with the given node id in the tree or `None` if the node is not found.
170    ///
171    /// # Example
172    ///
173    /// ```rust
174    /// # use tree_ds::prelude::{Node, Tree};
175    ///
176    /// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
177    ///
178    /// let node = Node::new(1, Some(2));
179    /// let node_id = tree.add_node(node.clone(), None).unwrap();
180    ///
181    /// assert_eq!(tree.get_node_by_id(&node_id), Some(node));
182    /// ```
183    pub fn get_node_by_id(&self, node_id: &Q) -> Option<Node<Q, T>> {
184        self.nodes
185            .iter()
186            .find(|n| &n.get_node_id().expect("Error: Failed to get the node Id.") == node_id)
187            .cloned()
188    }
189
190    /// Get the root node of the tree.
191    ///
192    /// This method gets the root node of the tree. The root node is the topmost node in the tree. The
193    /// root node has no parent node.
194    ///
195    /// # Returns
196    ///
197    /// The root node of the tree or `None` if the tree has no root node.
198    ///
199    /// # Example
200    ///
201    /// ```rust
202    /// # use tree_ds::prelude::{Node, Tree};
203    ///
204    /// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
205    ///
206    /// let node = Node::new(1, Some(2));
207    /// tree.add_node(node.clone(), None).unwrap();
208    ///
209    /// assert_eq!(tree.get_root_node(), Some(node));
210    /// ```
211    pub fn get_root_node(&self) -> Option<Node<Q, T>> {
212        self.nodes
213            .iter()
214            .find(|n| {
215                n.get_parent_id()
216                    .expect("Error: Failed to get the node Id of the parent.")
217                    .is_none()
218            })
219            .cloned()
220    }
221
222    /// Get the height of the node.
223    ///
224    /// This method gets the height of the node. The height of the node is the number of edges present
225    /// in the longest path connecting the node to a leaf node.
226    ///
227    /// # Returns
228    ///
229    /// The height of the node. If the node is a leaf node, the height is 0.  This method returns an
230    /// error if the node is not found in the tree.
231    ///
232    /// # Example
233    ///
234    /// ```rust
235    /// # use tree_ds::prelude::{Node, Tree};
236    ///
237    /// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
238    ///
239    /// let node_1 = tree.add_node(Node::new(1, Some(2)), None).unwrap();
240    /// let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1)).unwrap();
241    /// let node_3 = tree.add_node(Node::new(3, Some(6)), Some(&node_2)).unwrap();
242    ///
243    /// assert!(tree.get_node_height(&node_2).is_ok());
244    /// assert_eq!(tree.get_node_height(&node_2).unwrap(), 1);
245    /// ```
246    pub fn get_node_height(&self, node_id: &Q) -> crate::prelude::Result<i32> {
247        let node = self
248            .get_node_by_id(node_id)
249            .ok_or(NodeNotFound(node_id.to_string()))?;
250        let children = node.get_children_ids()?;
251        if children.is_empty() {
252            return Ok(0);
253        }
254        let mut height = 0;
255        for child in children {
256            let child_height = self.get_node_height(&child)?;
257            if child_height > height {
258                height = child_height;
259            }
260        }
261        Ok(height + 1)
262    }
263
264    /// Get the depth of a node in the tree.
265    ///
266    /// This method gets the depth of a node in the tree. The depth of a node is the length of the path
267    /// from the root node to the node. The depth of the node is the number of edges on the path from the
268    /// root node to the node.
269    ///
270    /// # Arguments
271    ///
272    /// * `node_id` - The id of the node.
273    ///
274    /// # Returns
275    ///
276    /// The depth of the node in the tree.  This method returns an error if the node is not found in the tree.
277    ///
278    /// # Example
279    ///
280    /// ```rust
281    /// # use tree_ds::prelude::{Node, Tree};
282    ///
283    /// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
284    ///
285    /// let node_1 = tree.add_node(Node::new(1, Some(2)), None).unwrap();
286    /// let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1)).unwrap();
287    /// let node_3 = tree.add_node(Node::new(3, Some(6)), Some(&node_2)).unwrap();
288    /// let depth_result = tree.get_node_depth(&node_3);
289    /// assert!(depth_result.is_ok());
290    /// assert_eq!(depth_result.unwrap(), 2);
291    /// ```
292    pub fn get_node_depth(&self, node_id: &Q) -> crate::prelude::Result<i32> {
293        let node = self
294            .get_node_by_id(node_id)
295            .ok_or(NodeNotFound(node_id.to_string()))?;
296        let mut depth = 0;
297        let mut parent = node.get_parent_id()?;
298        while let Some(parent_id) = parent {
299            depth += 1;
300            parent = self
301                .get_node_by_id(&parent_id)
302                .ok_or(NodeNotFound(parent_id.to_string()))?
303                .get_parent_id()?;
304        }
305        Ok(depth)
306    }
307
308    /// Get the ancestors of a node in the tree.
309    ///
310    /// This method gets the ancestors of a node in the tree. The ancestors of a node are all the nodes
311    /// that are on the path from the root node to the node, not including the node itself.
312    ///
313    /// # Arguments
314    ///
315    /// * `node_id` - The id of the node.
316    ///
317    /// # Returns
318    ///
319    /// The ancestors of the node from closest to furthest.  This method returns an error if the node is not found in the tree.
320    ///
321    /// # Example
322    ///
323    /// ```rust
324    /// # use tree_ds::prelude::{Node, Tree};
325    ///
326    /// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
327    ///
328    /// let node_1 = tree.add_node(Node::new(1, Some(2)), None).unwrap();
329    /// let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1)).unwrap();
330    /// let node_3 = tree.add_node(Node::new(3, Some(6)), Some(&node_2)).unwrap();
331    /// let depth_result = tree.get_ancestor_ids(&node_3);
332    /// assert!(depth_result.is_ok());
333    /// assert_eq!(depth_result.unwrap(), vec![2, 1]);
334    /// ```
335    pub fn get_ancestor_ids(&self, node_id: &Q) -> crate::prelude::Result<Vec<Q>> {
336        let node = self
337            .get_node_by_id(node_id)
338            .ok_or(NodeNotFound(node_id.to_string()))?;
339        let mut ancestors = vec![];
340        let mut parent = node.get_parent_id()?;
341        while let Some(parent_id) = parent {
342            ancestors.push(parent_id.clone());
343            parent = self
344                .get_node_by_id(&parent_id)
345                .ok_or(NodeNotFound(parent_id.to_string()))?
346                .get_parent_id()?;
347        }
348        Ok(ancestors)
349    }
350
351    /// Get the height of the tree.
352    ///
353    /// This method gets the height of the tree. The height of the tree is the length of the longest path
354    /// from the root node to a leaf node. The height of the tree is the number of edges on the longest
355    /// path from the root node to a leaf node.
356    ///
357    /// # Returns
358    ///
359    /// The height of the tree. This method returns an error if the tree has no root node.
360    ///
361    /// # Example
362    ///
363    /// ```rust
364    /// # use tree_ds::prelude::{Node, Tree, Result};
365    ///
366    /// # fn main() -> Result<()> {
367    /// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
368    ///
369    /// let node_1 = tree.add_node(Node::new(1, Some(2)), None)?;
370    /// let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1))?;
371    /// let node_3 = tree.add_node(Node::new(3, Some(6)), Some(&node_2))?;
372    /// let tree_height = tree.get_height();
373    /// assert!(tree_height.is_ok());
374    /// assert_eq!(tree_height?, 2);
375    /// # Ok(())
376    /// # }
377    /// ```
378    pub fn get_height(&self) -> crate::prelude::Result<i32> {
379        let root = self
380            .get_root_node()
381            .ok_or(InvalidOperation(String::from("Tree has no root node")))?;
382        self.get_node_height(&root.get_node_id()?)
383    }
384
385    /// Get the degree of a node in the tree.
386    ///
387    /// This method gets the degree of a node in the tree. The degree of a node is the number of children
388    /// that the node has.
389    ///
390    /// # Arguments
391    ///
392    /// * `node_id` - The id of the node.
393    ///
394    /// # Returns
395    ///
396    /// The degree of the node in the tree. This method returns an error if the node is not found in the tree.
397    ///
398    /// # Example
399    ///
400    /// ```rust
401    /// # use tree_ds::prelude::{Result, Node, Tree};
402    ///
403    /// # fn main() -> Result<()> {
404    /// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
405    ///
406    /// let node_1 = tree.add_node(Node::new(1, Some(2)), None)?;
407    /// let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1))?;
408    /// let node_3 = tree.add_node(Node::new(3, Some(6)), Some(&node_1))?;
409    ///
410    /// assert_eq!(tree.get_node_degree(&node_1)?, 2);
411    /// assert_eq!(tree.get_node_degree(&node_2)?, 0);
412    /// assert_eq!(tree.get_node_degree(&node_3)?, 0);
413    /// # Ok(())
414    /// # }
415    /// ```
416    pub fn get_node_degree(&self, node_id: &Q) -> crate::prelude::Result<i32> {
417        let node = self
418            .get_node_by_id(node_id)
419            .ok_or(NodeNotFound(node_id.to_string()))?;
420        Ok(node.get_children_ids()?.len() as i32)
421    }
422
423    /// Get the nodes in the tree.
424    ///
425    /// This method gets the nodes in the tree.
426    ///
427    /// # Returns
428    ///
429    /// The nodes in the tree.
430    ///
431    /// # Example
432    ///
433    /// ```rust
434    /// # use tree_ds::prelude::{Node, Tree};
435    ///
436    /// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
437    ///
438    /// let node = Node::new(1, Some(2));
439    /// tree.add_node(node.clone(), None).unwrap();
440    ///
441    /// assert_eq!(tree.get_nodes().len(), 1);
442    /// ```
443    pub fn get_nodes(&self) -> &Nodes<Q, T> {
444        self.nodes.as_ref()
445    }
446
447    /// Remove a node from the tree.
448    ///
449    /// This method removes a node from the tree. The node is removed using the given removal strategy.
450    /// The removal strategy determines how the node and its children are removed from the tree. The
451    /// `RetainChildren` strategy retains the children of the node when the node is removed. The
452    /// `RemoveNodeAndChildren` strategy removes the node and its children when the node is removed.
453    ///
454    /// # Arguments
455    ///
456    /// * `node_id` - The id of the node to remove.
457    /// * `strategy` - The strategy to use when removing the node.
458    ///
459    /// # Returns
460    /// An error if the node is not found in the tree or if the node is the root node and the removal
461    /// strategy is `RetainChildren`.
462    ///
463    /// # Example
464    ///
465    /// ```rust
466    /// # use tree_ds::prelude::{Node, Tree, NodeRemovalStrategy, Result};
467    ///
468    /// # fn main() -> Result<()> {
469    /// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
470    ///
471    /// let node_1 = tree.add_node(Node::new(1, Some(2)), None)?;
472    /// let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1))?;
473    /// tree.add_node(Node::new(3, Some(6)), Some(&node_2))?;
474    ///
475    /// tree.remove_node(&node_2, NodeRemovalStrategy::RetainChildren)?;
476    /// assert_eq!(tree.get_nodes().len(), 2);
477    /// # Ok(())
478    /// # }
479    /// ```
480    pub fn remove_node(
481        &mut self,
482        node_id: &Q,
483        strategy: NodeRemovalStrategy,
484    ) -> crate::prelude::Result<()> {
485        match strategy {
486            NodeRemovalStrategy::RetainChildren => {
487                let node = self
488                    .get_node_by_id(node_id)
489                    .ok_or(NodeNotFound(node_id.to_string()))?;
490                let parent_node_id = &node.get_parent_id()?.ok_or(InvalidOperation(
491                    String::from("Cannot remove root node with RetainChildren strategy"),
492                ))?;
493                let parent_node = self
494                    .get_node_by_id(parent_node_id)
495                    .ok_or(NodeNotFound(parent_node_id.to_string()))?;
496                parent_node.remove_child(node.clone())?;
497                let children = node.get_children_ids()?;
498                for child in children {
499                    if let Some(child) = self.get_node_by_id(&child) {
500                        parent_node.add_child(child)?;
501                    }
502                }
503                self.nodes.retain(|n| {
504                    &n.get_node_id().expect("Error: Failed to get the node Id.") != node_id
505                });
506                Ok(())
507            }
508            NodeRemovalStrategy::RemoveNodeAndChildren => {
509                let node = self
510                    .get_node_by_id(node_id)
511                    .ok_or(NodeNotFound(node_id.to_string()))?;
512                let children = node.get_children_ids()?;
513                if let Some(parent_id) = node.get_parent_id()? {
514                    let parent = self
515                        .get_node_by_id(&parent_id)
516                        .ok_or(NodeNotFound(parent_id.to_string()))?;
517                    parent.remove_child(node.clone())?;
518                }
519                self.nodes.retain(|n| {
520                    &n.get_node_id().expect("Error: Failed to get the node Id.") != node_id
521                });
522                for child in children {
523                    let child = self
524                        .get_node_by_id(&child)
525                        .ok_or(NodeNotFound(child.to_string()))?;
526                    node.remove_child(child.clone())?;
527                    self.remove_node(&child.get_node_id()?, strategy)?;
528                }
529                Ok(())
530            }
531        }
532    }
533
534    /// Get a subsection of the tree.
535    ///
536    /// This method gets a subsection of the tree starting from the node with the given node id. The
537    /// subsection is a list of nodes that are descendants of the node with the given node id upto the
538    /// given number of descendants. If the number of descendants is `None`, all the descendants of the
539    /// node are included in the subsection.
540    ///
541    /// # Arguments
542    ///
543    /// * `node_id` - The id of the node to get the subsection from.
544    /// * `generations` - The number of descendants to include in the subsection. If `None`, all the descendants of the node are included in the subsection.
545    ///
546    /// # Returns
547    ///
548    /// The subsection of the tree starting from the node with the given node id.
549    ///
550    /// # Example
551    ///
552    /// ```rust
553    /// # use tree_ds::prelude::{Node, Tree};
554    ///
555    /// # fn main() -> tree_ds::prelude::Result<()> {
556    /// # let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
557    ///
558    /// let node_1 = tree.add_node(Node::new(1, Some(2)), None)?;
559    /// let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1))?;
560    /// let node_3 = tree.add_node(Node::new(3, Some(6)), Some(&node_2))?;
561    ///
562    /// let subsection = tree.get_subtree(&node_2, None)?;
563    /// assert_eq!(subsection.get_nodes().len(), 2);
564    /// # Ok(())
565    /// # }
566    /// ```
567    pub fn get_subtree(
568        &self,
569        node_id: &Q,
570        generations: Option<i32>,
571    ) -> crate::prelude::Result<SubTree<Q, T>> {
572        let mut subsection = Nodes::default();
573        let node = self
574            .get_node_by_id(node_id)
575            .ok_or(NodeNotFound(node_id.to_string()))?;
576        subsection.push(node.clone());
577        // Get the subsequent children of the node recursively for the number of generations and add them to the subsection.
578        if let Some(generations) = generations {
579            let children = node.get_children_ids()?;
580            for current_generation in 0..generations {
581                for child in children.clone() {
582                    subsection.append(
583                        &mut self
584                            .get_subtree(&child, Some(current_generation))?
585                            .get_nodes()
586                            .clone(),
587                    );
588                }
589            }
590        } else {
591            let children = node.get_children_ids()?;
592            for child in children {
593                subsection.append(&mut self.get_subtree(&child, None)?.get_nodes().clone());
594            }
595        }
596
597        Ok(SubTree {
598            name: Some(node_id.to_string()),
599            nodes: subsection,
600        })
601    }
602
603    /// Get the siblings of a node in the tree.
604    ///
605    /// This method gets the siblings of a node in the tree. The siblings of a node are the children
606    /// that share the same parent as the node.
607    ///
608    /// # Arguments
609    ///
610    /// * `node_id` - The id of the node to get the siblings of.
611    /// * `inclusive` - A flag that indicates whether to include the node in the siblings list.
612    ///
613    /// # Returns
614    ///
615    /// The siblings of the node in the tree.
616    ///
617    /// # Example
618    ///
619    /// ```rust
620    /// # use tree_ds::prelude::{Node, Tree};
621    ///
622    /// # fn main() -> tree_ds::prelude::Result<()> {
623    /// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
624    /// let node_1 = tree.add_node(Node::new(1, Some(2)), None)?;
625    /// let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1))?;
626    /// tree.add_node(Node::new(3, Some(6)), Some(&node_1))?;
627    /// tree.add_node(Node::new(4, Some(7)), Some(&node_1))?;
628    ///
629    /// let siblings = tree.get_sibling_ids(&node_2, false)?;
630    /// assert_eq!(siblings.len(), 2);
631    ///
632    /// let siblings = tree.get_sibling_ids(&node_2, true)?;
633    /// assert_eq!(siblings.len(), 3);
634    /// # Ok(())
635    /// # }
636    /// ```
637    pub fn get_sibling_ids(&self, node_id: &Q, inclusive: bool) -> crate::prelude::Result<Vec<Q>> {
638        let node = self
639            .get_node_by_id(node_id)
640            .ok_or(NodeNotFound(node_id.to_string()))?;
641        if let Some(parent_id) = node.get_parent_id()? {
642            let parent = self
643                .get_node_by_id(&parent_id)
644                .ok_or(NodeNotFound(parent_id.to_string()))?;
645            if inclusive {
646                parent.get_children_ids()
647            } else {
648                Ok(parent
649                    .get_children_ids()?
650                    .iter()
651                    .filter(|x| *x != node_id)
652                    .cloned()
653                    .collect())
654            }
655        } else if inclusive {
656            // We need to clone this since Q does not implement Copy.
657            Ok(vec![node_id.clone()])
658        } else {
659            Ok(vec![])
660        }
661    }
662
663    /// Add a subsection to the tree.
664    ///
665    /// This method adds a subsection to the tree. The subsection is a list of nodes that are descendants
666    /// of the node with the given node id. The subsection is added as children of the node with the
667    /// given node id.
668    ///
669    /// # Arguments
670    ///
671    /// * `node_id` - The id of the node to add the subsection to.
672    /// * `subtree` - The subsection to add to the tree.
673    ///
674    /// # Returns
675    /// This function return an error if:
676    /// - The node is not found in the tree.
677    /// - The subsection has no root node.
678    ///
679    /// # Example
680    ///
681    /// ```rust
682    /// # use tree_ds::prelude::{Node, Tree, SubTree};
683    ///
684    /// # fn main() -> tree_ds::prelude::Result<()> {
685    /// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
686    /// let node_id = tree.add_node(Node::new(1, Some(2)), None)?;
687    /// let mut subtree = SubTree::new(Some("Sample Tree"));
688    /// let node_2 = subtree.add_node(Node::new(2, Some(3)), None)?;
689    /// subtree.add_node(Node::new(3, Some(6)), Some(&node_2))?;
690    /// tree.add_subtree(&node_id, subtree)?;
691    /// assert_eq!(tree.get_nodes().len(), 3);
692    /// # Ok(())
693    /// # }
694    /// ```
695    pub fn add_subtree(
696        &mut self,
697        node_id: &Q,
698        subtree: SubTree<Q, T>,
699    ) -> crate::prelude::Result<()> {
700        let node = self
701            .get_node_by_id(node_id)
702            .ok_or(NodeNotFound(node_id.to_string()))?;
703        // Get the root node in the subsection and add it as a child of the node.
704        let subtree_nodes = subtree.get_nodes();
705        let root_node = subtree
706            .get_root_node()
707            .ok_or(InvalidOperation(String::from("Subtree has no root node.")))?;
708        node.add_child(root_node.clone())?;
709        self.nodes.append(&mut subtree_nodes.clone());
710        Ok(())
711    }
712
713    /// Traverse the subtree from the given node.
714    ///
715    /// This method traverses the subtree from the given node in the given order.
716    ///
717    /// # Arguments
718    ///
719    /// * `order` - The order to traverse the tree.
720    /// * `node_id` - The id of the node to start the traversal from.
721    ///
722    /// # Returns
723    ///
724    /// The nodes in the tree in the given order. This method returns an error if the node is not found
725    /// in the tree.
726    ///
727    /// # Example
728    ///
729    /// ```rust
730    /// # use tree_ds::prelude::{Node, Tree, TraversalStrategy};
731    ///
732    /// # fn main() -> tree_ds::prelude::Result<()> {
733    /// let mut tree: Tree<i32, i32> = Tree::new(Some("Sample Tree"));
734    /// let node_1 = tree.add_node(Node::new(1, Some(2)), None)?;
735    /// let node_2 = tree.add_node(Node::new(2, Some(3)), Some(&node_1))?;
736    /// let node_3 = tree.add_node(Node::new(3, Some(6)), Some(&node_2))?;
737    ///
738    /// let ordered_nodes = tree.traverse(&node_1, TraversalStrategy::PreOrder)?;
739    /// # let expected = vec![1, 2, 3];
740    /// # assert_eq!(ordered_nodes, expected);
741    /// # Ok(())
742    /// # }
743    /// ```
744    pub fn traverse(
745        &self,
746        node_id: &Q,
747        order: TraversalStrategy,
748    ) -> crate::prelude::Result<Vec<Q>> {
749        let mut nodes = vec![];
750        let node = self
751            .get_node_by_id(node_id)
752            .ok_or(NodeNotFound(node_id.to_string()))?;
753        match &order {
754            TraversalStrategy::PreOrder => {
755                nodes.push(node_id.clone());
756                for child_id in node.get_children_ids()?.iter() {
757                    nodes.append(&mut self.traverse(child_id, order)?);
758                }
759            }
760            TraversalStrategy::PostOrder => {
761                for child_id in node.get_children_ids()?.iter() {
762                    nodes.append(&mut self.traverse(child_id, order)?);
763                }
764                nodes.push(node_id.clone());
765            }
766            TraversalStrategy::InOrder => {
767                for (index, child_id) in node.get_children_ids()?.iter().enumerate() {
768                    if index == 0 {
769                        nodes.append(&mut self.traverse(child_id, order)?);
770                        if !nodes.contains(child_id) {
771                            nodes.push(child_id.clone());
772                        }
773                        if !nodes.contains(node_id) {
774                            nodes.push(node_id.clone());
775                        }
776                    } else {
777                        nodes.push(child_id.clone());
778                        nodes.append(&mut self.traverse(child_id, order)?);
779                    }
780                }
781            }
782        }
783        #[cfg(not(feature = "no_std"))]
784        let mut seen = HashSet::new();
785        #[cfg(feature = "no_std")]
786        let mut seen = BTreeSet::new();
787        nodes.retain(|x| seen.insert(x.clone()));
788        Ok(nodes)
789    }
790
791    /// Print the tree.
792    ///
793    /// This method prints the tree to the standard output.
794    #[doc(hidden)]
795    fn print_tree(tree: &Tree<Q, T>, f: &mut Formatter<'_>) -> crate::prelude::Result<()>
796    where
797        Q: PartialEq + Eq + Clone + Display + Hash,
798        T: PartialEq + Eq + Clone + Display + Default,
799    {
800        Tree::print_sub_tree(
801            tree,
802            f,
803            &tree.get_root_node().ok_or(FmtError)?,
804            String::new(),
805            true,
806        )?;
807        Ok(())
808    }
809
810    fn print_sub_tree(
811        tree: &Tree<Q, T>,
812        f: &mut Formatter<'_>,
813        root_node: &Node<Q, T>,
814        mut parent_prefix: String,
815        is_last_child: bool,
816    ) -> crate::prelude::Result<()>
817    where
818        Q: PartialEq + Eq + Clone + Display + Hash,
819        T: PartialEq + Eq + Clone + Display + Default,
820    {
821        write!(f, "{parent_prefix}")?;
822        if is_last_child {
823            if tree
824                .get_root_node()
825                .is_some_and(|x| x.get_node_id() == root_node.get_node_id())
826            {
827                writeln!(f, "{root_node}")?;
828            } else {
829                writeln!(f, "└── {root_node}")?;
830                parent_prefix = format!("{parent_prefix}    ");
831            }
832        } else {
833            writeln!(f, "├── {root_node}")?;
834            parent_prefix = format!("{parent_prefix}│   ");
835        }
836        let children = root_node.get_children_ids()?;
837        for (index, node_id) in children.iter().enumerate() {
838            let node = tree
839                .get_node_by_id(node_id)
840                .ok_or(NodeNotFound(node_id.to_string()))?;
841
842            Tree::print_sub_tree(
843                tree,
844                f,
845                &node,
846                parent_prefix.clone(),
847                index == children.len() - 1,
848            )?;
849        }
850        Ok(())
851    }
852}
853
854impl<Q, T> Default for Tree<Q, T>
855where
856    Q: PartialEq + Eq + Clone,
857    T: PartialEq + Eq + Clone,
858{
859    /// Create a new tree with no nodes.
860    fn default() -> Self {
861        Tree {
862            name: None,
863            nodes: Nodes::default(),
864        }
865    }
866}
867
868impl<Q, T> Display for Tree<Q, T>
869where
870    Q: PartialEq + Eq + Clone + Display + Hash + Ord,
871    T: PartialEq + Eq + Clone + Display + Default,
872{
873    /// Print the tree.
874    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
875        if let Some(name) = &self.name {
876            writeln!(f, "{name}")?;
877            writeln!(
878                f,
879                "{}",
880                name.clone().chars().map(|_| "*").collect::<String>()
881            )?;
882        }
883        Tree::print_tree(self, f).map_err(|_| FmtError)?;
884        Ok(())
885    }
886}
887
888impl<Q, T> Drop for Tree<Q, T>
889where
890    Q: PartialEq + Eq + Clone,
891    T: PartialEq + Eq + Clone,
892{
893    /// Drop the tree.
894    #[doc(hidden)]
895    fn drop(&mut self) {
896        self.nodes.clear();
897    }
898}
899
900#[cfg(feature = "serde")]
901impl<Q, T> Serialize for Tree<Q, T>
902where
903    Q: PartialEq + Eq + Clone + Serialize,
904    T: PartialEq + Eq + Clone + Serialize,
905{
906    /// Serialize the tree.
907    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
908    where
909        S: serde::Serializer,
910    {
911        if self.name.is_none() {
912            let mut state = serializer.serialize_struct("Tree", 1)?;
913            state.serialize_field("nodes", &self.nodes)?;
914            return state.end();
915        }
916        let mut state = serializer.serialize_struct("Tree", 2)?;
917        state.serialize_field("name", &self.name)?;
918        state.serialize_field("nodes", &self.nodes)?;
919        state.end()
920    }
921}
922
923#[cfg(feature = "serde")]
924impl<'de, Q, T> Deserialize<'de> for Tree<Q, T>
925where
926    Q: PartialEq + Eq + Clone + Deserialize<'de>,
927    T: PartialEq + Eq + Clone + Deserialize<'de>,
928{
929    /// Deserialize the tree.
930    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
931    where
932        D: serde::Deserializer<'de>,
933    {
934        #[derive(Deserialize)]
935        struct TreeVisitor<Q, T>
936        where
937            Q: PartialEq + Eq + Clone,
938            T: PartialEq + Eq + Clone,
939        {
940            name: Option<String>,
941            nodes: Nodes<Q, T>,
942        }
943
944        let tree_visitor: TreeVisitor<Q, T> = Deserialize::deserialize(deserializer)?;
945        let tree = Tree {
946            name: tree_visitor.name,
947            nodes: tree_visitor.nodes,
948        };
949        Ok(tree)
950    }
951}