Last active
October 29, 2019 18:10
-
-
Save kevgathuku/7f4e1f54daba340df5eea462a8bdeb4d to your computer and use it in GitHub Desktop.
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 tree = Leaf | Node(int, tree, tree); | |
let rec sum = (item) => { | |
switch (item) { | |
| Leaf => 0 | |
| Node(value, left, right) => value + sum(left) + sum(right); | |
} | |
}; | |
let rec height = (root) => { | |
switch (root) { | |
| Leaf => 0 | |
| Node(_, left, right) => 1 + (height(left) > height(right) ? height(left) : height(right)); | |
} | |
} | |
let myTree = | |
Node( | |
1, | |
Node(2, Node(4, Leaf, Leaf), Node(6, Leaf, Leaf)), | |
Node(3, Node(5, Leaf, Leaf), Node(7, Leaf, Leaf)) | |
); | |
let customTree = | |
Node( | |
8, | |
Node(3, Node(1, Leaf, Leaf), Node(6, Node(4, Leaf, Leaf), Node(7, Leaf, Leaf))), | |
Node(10, Leaf, Node(14, Node(13, Leaf, Leaf), Leaf)) | |
); | |
Js.log(sum(myTree)); | |
Js.log(height(myTree)); | |
Js.log(sum(customTree)); | |
Js.log(height(customTree)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment