Added Tree type and implementations
This commit is contained in:
parent
3160227bfc
commit
38f0c14ce8
2 changed files with 45 additions and 2 deletions
|
@ -1,3 +1,18 @@
|
||||||
fn main() {
|
mod tree;
|
||||||
println!("Hello, world!");
|
|
||||||
|
fn build_tree(h: u32) -> Option<Box<tree::Tree>> {
|
||||||
|
let mut result: Option<Box<tree::Tree>> = None;
|
||||||
|
|
||||||
|
if h != 0 {
|
||||||
|
result = Some(tree::concat_trees(h, build_tree(h - 1), build_tree(h - 1)));
|
||||||
|
}
|
||||||
|
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let tree: tree::Tree = *build_tree(25).expect("Error getting result from build tree.");
|
||||||
|
|
||||||
|
println!("Resulting tree from build_tree.");
|
||||||
|
println!("{}", tree);
|
||||||
}
|
}
|
28
gemla/src/tree/mod.rs
Normal file
28
gemla/src/tree/mod.rs
Normal file
|
@ -0,0 +1,28 @@
|
||||||
|
use std::fmt;
|
||||||
|
|
||||||
|
pub struct Tree {
|
||||||
|
val: u32,
|
||||||
|
left: Option<Box<Tree>>,
|
||||||
|
right: Option<Box<Tree>>
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn concat_trees(v: u32, l: Option<Box<Tree>>, r: Option<Box<Tree>>) -> Box<Tree> {
|
||||||
|
Box::new(Tree {
|
||||||
|
val: v,
|
||||||
|
left: l,
|
||||||
|
right: r
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for Tree {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
let node_str = |t: &Option<Box<Tree>>| -> String {
|
||||||
|
match t {
|
||||||
|
Some(n) => format!("{}", *n),
|
||||||
|
_ => String::from("_")
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
write!(f, "({} :{}|{})", self.val, node_str(&self.left), node_str(&self.right))
|
||||||
|
}
|
||||||
|
}
|
Loading…
Add table
Reference in a new issue