Skip to content

Commit 6daf643

Browse files
lywjoelremo5000
authored andcommitted
Add Tree library (#373)
* add tree.js, update index.js * remove TREE case from loadLib
1 parent 1ae4431 commit 6daf643

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

public/externalLibs/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ function loadAllLibs() {
3232
// list visualizer
3333
'/externalLibs/visualizer/KineticJS.js',
3434
'/externalLibs/visualizer/visualizer.js',
35+
// binary tree library
36+
'/externalLibs/tree.js',
3537
];
3638

3739
for (var i = 0; i < files.length; i++) {

public/externalLibs/tree.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// tree.js: Binary Tree abstraction for M5
2+
// requires list.js
3+
4+
// Author: Joel Lee
5+
6+
// make_empty_binary_tree returns an empty list
7+
function make_empty_binary_tree() {
8+
return [];
9+
}
10+
11+
// checks if a given list is a valid binary tree, according to the abstraction
12+
function is_binary_tree(t) {
13+
return (is_empty_binary_tree(t) ||
14+
((length(t) === 3)
15+
&& is_binary_tree(left_subtree_of(t))
16+
&& is_binary_tree(right_subtree_of(t))));
17+
}
18+
19+
// make_binary_tree_node returns a binary tree node composed of the
20+
// three elements passed in
21+
function make_binary_tree_node(left, value, right) {
22+
if (!is_binary_tree(left)) {
23+
throw new Error("Left subtree is not a valid binary tree");
24+
} else if (!is_binary_tree(right)) {
25+
throw new Error("Right subtree is not a valid binary tree");
26+
}
27+
return list(left, value, right);
28+
}
29+
30+
// is_empty_binary_tree checks if given binary tree node is an empty list
31+
function is_empty_binary_tree(t) {
32+
return is_empty_list(t);
33+
}
34+
35+
// left_subtree_of returns the left subtree of a given binary tree node
36+
function left_subtree_of(t) {
37+
return list_ref(t, 0);
38+
}
39+
40+
// value_of returns the value of a given binary tree node
41+
function value_of(t) {
42+
return list_ref(t, 1);
43+
}
44+
45+
// right_subtree_of returns the right subtree of a given binary tree node
46+
function right_subtree_of(t) {
47+
return list_ref(t, 2);
48+
}
49+

0 commit comments

Comments
 (0)