Last active
February 9, 2018 03:39
-
-
Save Spuffynism/596093f44bb098159faa876811d46137 to your computer and use it in GitHub Desktop.
binary tree visiting algorithms
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 'a binary_tree = Leaf | Node of 'a * 'a binary_tree * 'a binary_tree;; | |
| let visit_binary_tree tree (visiting_function:'a binary_tree -> 'a list) :'a list = match tree with | |
| | Leaf -> [] | |
| | Node (_, _, _) -> visiting_function tree;; | |
| (* | |
| 1 | |
| / \ | |
| 2 3 | |
| / \ \ | |
| 4 5 6 | |
| *) | |
| let t = Node(1, Node(2, Node(4, Leaf, Leaf), Node(5, Leaf, Leaf)), Node(3, Leaf, Node(6, Leaf, Leaf))); | |
| let get_root_node_value (tree: 'a binary_tree) : int = match tree with | |
| | Leaf -> 0 | |
| | Node (v, _, _) -> v;; | |
| let rec symmetric_visit (tree: 'a binary_tree) : 'a list = match tree with | |
| | Leaf -> [] | |
| | Node (v, left_tree, right_tree) -> symmetric_visit (left_tree) @ [v] @ symmetric_visit (right_tree);; | |
| let rec preorder_visit (tree: 'a binary_tree) : 'a list = match tree with | |
| | Leaf -> [] | |
| | Node (v, left_tree, right_tree) -> [v] @ symmetric_visit (left_tree) @ symmetric_visit (right_tree);; | |
| let rec postorder_visit (tree: 'a binary_tree) : 'a list = match tree with | |
| | Leaf -> [] | |
| | Node (v, left_tree, right_tree) -> symmetric_visit (left_tree) @ symmetric_visit (right_tree) @ [v];; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment