Skip to content

Commit 3ce078a

Browse files
committed
Add enum based rust solution for binarytrees
1 parent 8f8a9f7 commit 3ce078a

File tree

1 file changed

+53
-0
lines changed
  • bench/algorithm/binarytrees

1 file changed

+53
-0
lines changed

bench/algorithm/binarytrees/6.rs

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
use std::cmp::max;
2+
3+
enum TreeNode {
4+
Leaf,
5+
Node(Box<TreeNode>, Box<TreeNode>),
6+
}
7+
8+
impl TreeNode {
9+
fn check(&self) -> usize {
10+
match &self {
11+
TreeNode::Leaf => 1,
12+
TreeNode::Node(left, right) => 1 + left.check() + right.check(),
13+
}
14+
}
15+
16+
fn create(depth: usize) -> Box<TreeNode> {
17+
if depth > 0 {
18+
let next_depth = depth - 1;
19+
Box::new(TreeNode::Node(Self::create(next_depth), Self::create(next_depth)))
20+
} else {
21+
Box::new(TreeNode::Leaf)
22+
}
23+
}
24+
}
25+
26+
const MIN_DEPTH: usize = 4;
27+
28+
fn main() {
29+
let n = std::env::args_os()
30+
.nth(1)
31+
.and_then(|s| s.into_string().ok())
32+
.and_then(|n| n.parse().ok())
33+
.unwrap_or(10);
34+
35+
let max_depth = max(MIN_DEPTH + 2, n);
36+
let stretch_depth = max_depth + 1;
37+
38+
println!("stretch tree of depth {}\t check: {}", stretch_depth, TreeNode::create(stretch_depth).check());
39+
40+
let long_lived_tree = TreeNode::create(max_depth);
41+
42+
for iteration_depth in (MIN_DEPTH..stretch_depth).step_by(2) {
43+
let iterations = 1 << (max_depth - iteration_depth + MIN_DEPTH);
44+
let mut nodes = 0;
45+
for _ in 0..iterations {
46+
nodes += TreeNode::create(iteration_depth).check();
47+
}
48+
println!("{iterations}\t trees of depth {iteration_depth}\t check: {nodes}")
49+
}
50+
51+
let nodes = long_lived_tree.check();
52+
println!("long lived tree of depth {max_depth}\t check: {nodes}");
53+
}

0 commit comments

Comments
 (0)