Guest User

Untitled

a guest
Jul 19th, 2018
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.72 KB | None | 0 0
  1. use std::cmp::max;
  2.  
  3. trait TreeLike {
  4. fn height(&self) -> i32;
  5. }
  6.  
  7. struct Tree {
  8. left: Option<Box<Tree>>,
  9. right: Option<Box<Tree>>,
  10. value: i32
  11. }
  12.  
  13. impl TreeLike for Tree {
  14.  
  15. fn height(&self) -> i32 {
  16. 1 + max(self.left.height(), self.right.height())
  17. }
  18. }
  19.  
  20. impl TreeLike for Option<Box<Tree>> {
  21.  
  22. fn height(&self) -> i32 {
  23. match self {
  24. Some(ref tree) => tree.height(),
  25. None => 0,
  26. }
  27. }
  28. }
  29.  
  30. fn main() {
  31. let child = Tree {
  32. left: None,
  33. right: None,
  34. value: 3,
  35. };
  36. let parent = Tree {
  37. left: Some(Box::new(child)),
  38. right: None,
  39. value: 2,
  40. };
  41. let a = parent.height().to_string();
  42. println!("{0}", a);
  43. }
Add Comment
Please, Sign In to add comment