Advertisement
Guest User

Untitled

a guest
Jun 20th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. type Link<'a, T> = Option<Box<&'a Node<'a, T>>>;
  2.  
  3. pub struct Node<'a, T: std::fmt::Debug> {
  4. data: T,
  5. left: Link<'a, T>,
  6. right: Link<'a, T>,
  7. right_thread: bool,
  8. }
  9.  
  10. impl<'a, T: std::fmt::Debug> std::fmt::Debug for Node<'a, T> {
  11. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  12. write!(f, "Node: {:?}", self.data)
  13. }
  14. }
  15.  
  16. pub fn left_most<'a, T: std::fmt::Debug>(n: &'a Node<'a, T>) -> &'a Node<'a, T> {
  17. let mut _n = n;
  18.  
  19. loop {
  20. match &_n.left {
  21. Some(left) => _n = left,
  22. None => break,
  23. }
  24. }
  25.  
  26. _n
  27. }
  28.  
  29. pub fn in_order_traversal<'a, T: std::fmt::Debug>(root: &'a Node<'a, T>) {
  30. let mut cur: &'a Node<'a, T> = left_most(root);
  31.  
  32. loop {
  33. println!("{:?}", &cur);
  34.  
  35. match &cur.right {
  36. Some(right) => {
  37. if cur.right_thread {
  38. cur = right;
  39. } else {
  40. cur = left_most(right);
  41. }
  42. },
  43. None => break,
  44. }
  45. }
  46. }
  47.  
  48. fn main() {
  49. let mut root = Node {
  50. data: 6,
  51. left: None,
  52. right: None,
  53. right_thread: false
  54. };
  55.  
  56. let mut _node_1_1 = Node {
  57. data: 3,
  58. left: None,
  59. right: None,
  60. right_thread: true
  61. };
  62.  
  63. let mut _node_1_2 = Node {
  64. data: 8,
  65. left: None,
  66. right: None,
  67. right_thread: true
  68. };
  69.  
  70. {
  71. root.left = Some(Box::new(&_node_1_1));
  72. root.right = Some(Box::new(&_node_1_2));
  73. }
  74.  
  75. {
  76. _node_1_1.right = Some(Box::new(&root));
  77. _node_1_1.left = Some(Box::new(&root));
  78. }
  79.  
  80. { in_order_traversal(&root); }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement