Last active
June 16, 2019 13:34
-
-
Save dustinknopoff/13dc6e9fa313cba31a2f54573ca10006 to your computer and use it in GitHub Desktop.
Is a Tree reflexive?
This file contains hidden or 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
type OptionBranch = Option<Box<Tree>>; | |
#[derive(Debug)] | |
struct Tree { | |
data: i32, | |
branches: (OptionBranch, OptionBranch) | |
} | |
impl Tree { | |
fn new(data: i32) -> Self { | |
Tree { | |
data, | |
branches: (None, None) | |
} | |
} | |
fn add_branch_left(&mut self, data: i32) { | |
match &mut self.branches { | |
(Some(_), None) => self.branches.1 = Some(Box::new(Tree::new(data))), | |
(None, Some(_)) => self.branches.0 = Some(Box::new(Tree::new(data))), | |
(Some(x), Some(_)) => x.add_branch_left(data), | |
(None, None) => self.branches.0 = Some(Box::new(Tree::new(data))) | |
} | |
} | |
fn add_branch_right(&mut self, data: i32) { | |
match &mut self.branches { | |
(Some(_), None) => self.branches.1 = Some(Box::new(Tree::new(data))), | |
(None, Some(_)) => self.branches.0 = Some(Box::new(Tree::new(data))), | |
(Some(_), Some(y)) => y.add_branch_right(data), | |
(None, None) => self.branches.0 = Some(Box::new(Tree::new(data))) | |
} | |
} | |
} | |
fn is_reflexive(root: Tree) -> bool { | |
match root.branches { | |
(None, None) => true, | |
(Some(_), None) => false, | |
(None, Some(_)) => false, | |
(Some(left), Some(right)) => traverse((left, right)) | |
} | |
} | |
type Branch = Box<Tree>; | |
fn traverse((left_branch, right_branch): (Branch, Branch)) -> bool { | |
match (left_branch.branches, right_branch.branches) { | |
((None, None), (None, None)) => left_branch.data == right_branch.data, | |
((Some(x), None), (None, Some(y))) => traverse((x,y)), | |
((None, Some(x)), (Some(y), None)) => traverse((x,y)), | |
((Some(l_x), Some(l_y)), (Some(r_x), Some(r_y))) => traverse((l_x, r_y)) && traverse((l_y, r_x)), | |
_ => false | |
} | |
} | |
fn main() { | |
let mut root = Tree::new(1); | |
root.add_branch_left(2); | |
root.add_branch_right(2); | |
root.add_branch_left(3); | |
root.add_branch_left(4); | |
root.add_branch_right(4); | |
root.add_branch_right(3); | |
dbg!(is_reflexive(root)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
✅
❌