Skip to content

Instantly share code, notes, and snippets.

@jonathansty
Created February 4, 2019 10:57
Show Gist options
  • Save jonathansty/ebfbde49f5e56b1ebfc3b3966b92840a to your computer and use it in GitHub Desktop.
Save jonathansty/ebfbde49f5e56b1ebfc3b3966b92840a to your computer and use it in GitHub Desktop.

Revisions

  1. jonathansty created this gist Feb 4, 2019.
    51 changes: 51 additions & 0 deletions BinaryTree.rs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@

    struct Node<T: Ord> {
    data : T,

    left : Option<Box<Node<T>>>,
    right : Option<Box<Node<T>>>,
    }

    impl<T: Ord> Node<T> {
    pub fn new(data : T) -> Self {
    Node{
    data,
    left: None,
    right: None,
    }
    }

    }

    fn main() {
    // Setup a binary tree
    let mut parent = Box::new(Node::new(15));
    parent.left = Some(Box::new(Node::new(7)));

    if let Some(ref mut left) = parent.left {
    left.left = Some(Box::new(Node::new(3)));
    }

    parent.right = Some(Box::new(Node::new(30)));

    use std::collections::VecDeque;

    // Loop through a binary tree
    let mut stack = Vec::new();
    let mut current = Some(&parent);
    while current.is_some() || !stack.is_empty() {
    while current.is_some() {
    stack.push(current);
    current = current.unwrap().left.as_ref();
    }

    current = stack.pop().unwrap();
    dbg!(current.unwrap().data);

    current = current.unwrap().right.as_ref();
    }

    println!("Still can use parent here!");
    dbg!(parent.data);
    }