1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-06-19 23:45:40 +02:00

Binary tree exercise

This commit is contained in:
Alexandre Senges
2023-08-15 10:08:59 +00:00
parent 52284c7d13
commit 27f763ad56
2 changed files with 82 additions and 0 deletions

View File

@ -121,6 +121,7 @@
- [Exercises](exercises/day-2/afternoon.md) - [Exercises](exercises/day-2/afternoon.md)
- [Luhn Algorithm](exercises/day-2/luhn.md) - [Luhn Algorithm](exercises/day-2/luhn.md)
- [Strings and Iterators](exercises/day-2/strings-iterators.md) - [Strings and Iterators](exercises/day-2/strings-iterators.md)
- [Binary Tree](exercises/day-2/binary-tree.md)
# Day 3: Morning # Day 3: Morning

View File

@ -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?
<details open=false>
```rust
#[derive(Debug)]
struct BinaryTree {
value: Side,
left: Option<Box<Self>>,
right: Option<Box<Self>>
}
```
</details>
Let's now write a method to to create a BinaryTree with arbitrary depth:
<details open=false>
```rust
use Side::*;
impl BinaryTree {
fn new_with_depth(depth: i32, side: Side) -> Option<Box<BinaryTree>> {
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
}))
}
}
```
</details>
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`.
<details open=false>
```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;
}
}
```
</details>