Skip to content

Instantly share code, notes, and snippets.

@kevgathuku
Last active October 29, 2019 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevgathuku/7f4e1f54daba340df5eea462a8bdeb4d to your computer and use it in GitHub Desktop.
Save kevgathuku/7f4e1f54daba340df5eea462a8bdeb4d to your computer and use it in GitHub Desktop.
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