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