Created
December 21, 2018 07:43
-
-
Save j5ik2o/2da1b6b9ef8d47e787269c1346113606 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait BTree { | |
fn size(&self) -> i32; | |
fn sum(&self) -> i64; | |
fn min(&self) -> i64; | |
fn max(&self) -> i64; | |
fn find(&self, value: i64) -> Option<i64>; | |
} | |
enum Node { | |
Leaf { | |
value: i64 | |
}, | |
Branch { | |
left: Box<Node>, | |
value: i64, | |
right: Box<Node>, | |
}, | |
} | |
impl BTree for Node { | |
fn size(&self) -> i32 { | |
return match self { | |
Node::Leaf { value: _ } => { | |
1 | |
} | |
Node::Branch { left, value: _, right } => { | |
left.size() + 1 + right.size() | |
} | |
}; | |
} | |
fn sum(&self) -> i64 { | |
return match self { | |
Node::Leaf { value } => { | |
*value | |
} | |
Node::Branch { left, value, right } => { | |
left.sum() + *value + right.sum() | |
} | |
}; | |
} | |
fn min(&self) -> i64 { | |
return match self { | |
Node::Leaf { value } => { | |
*value | |
} | |
Node::Branch { left, value: _, right: _ } => { | |
left.min() | |
} | |
}; | |
} | |
fn max(&self) -> i64 { | |
return match self { | |
Node::Leaf { value } => { | |
*value | |
} | |
Node::Branch { left: _, value: _, right } => { | |
right.max() | |
} | |
}; | |
} | |
fn find(&self, _value: i64) -> Option<i64> { | |
return match self { | |
Node::Leaf { value } => { | |
if *value == _value { Some(*value) } else { None } | |
} | |
Node::Branch { left: _, value, right: _ } if *value == _value => { | |
Some(*value) | |
} | |
Node::Branch { ref left, value, right: _} if *value > _value => { | |
left.find(_value) | |
} | |
Node::Branch {left: _, value, ref right } if *value < _value => { | |
right.find(_value) | |
} | |
Node::Branch { left: _, value: _, right: _ } => { | |
None | |
} | |
}; | |
} | |
} | |
fn main() { | |
let node = Node::Branch { left: Box::new(Node::Leaf { value: 1 }), value: 2, right: Box::new(Node::Leaf { value: 3 }) }; | |
println!("Hello, world!: {}, {}, {}, {}, {}", node.size(), node.sum(), node.min(), node.max(), node.find(2).unwrap()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment