diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 218f69df..6a422d3a 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -121,6 +121,7 @@ - [Exercises](exercises/day-2/afternoon.md) - [Luhn Algorithm](exercises/day-2/luhn.md) - [Strings and Iterators](exercises/day-2/strings-iterators.md) + - [Binary Tree](exercises/day-2/binary-tree.md) # Day 3: Morning diff --git a/src/exercises/day-2/binary-tree.md b/src/exercises/day-2/binary-tree.md new file mode 100644 index 00000000..85f9cbba --- /dev/null +++ b/src/exercises/day-2/binary-tree.md @@ -0,0 +1,81 @@ +# Binary Tree + +A Binary Tree is a tree-type data structure where every node has two children (left and right). +We want to create a tree where each node would be assigned a variant `Left`, `Right` or `Root` +depdending on its original position related to its parent. The side is defined in the following enum: + +```rust +#[derive(Debug)] +enum Side { + Left, + Right, + Root +} +``` + +Using the data structures in the standard library, how can we represent such a Binary Tree in Rust? + +
+ +```rust +#[derive(Debug)] +struct BinaryTree { + value: Side, + left: Option>, + right: Option> +} +``` + +
+ +Let's now write a method to to create a BinaryTree with arbitrary depth: + +
+ +```rust +use Side::*; + +impl BinaryTree { + fn new_with_depth(depth: i32, side: Side) -> Option> { + if depth == 0 { + return None; + } + let left = Self::new_with_depth(depth - 1, Left); + let right = Self::new_with_depth(depth - 1, Right); + Some(Box::new(BinaryTree { + value: side, + left, + right + })) + } +} +``` + +
+ +Let's now write a method to invert the tree. To make sure that the tree is inverted, +left nodes values should now be `Right` and right nodes values should now be `Left`. + + +
+ +```rust +use Side::*; + +impl BinaryTree { + fn invert(&mut self) { + let mut left = self.left.take(); + if let Some(left) = &mut left { + left.invert(); + } + let mut right = self.right.take(); + if let Some(right) = &mut right { + right.invert(); + } + self.left = right; + self.right = left; + } +} +``` + +