Javascript: Binary tree aggregation

JS: Introduction to Object Oriented Programming (OOP)
Last update: 14 Jan 23:20
0
Students

In this test, we will use a binary tree, and perform data aggregation.

Node.js

Implement the following class methods:

  • getCount() returns the number of nodes in the tree
  • getSum() returns the sum of all tree keys
  • toArray() returns a one-dimensional array containing all keys
  • toString() returns a string representation of the tree
  • every(fn) verifies that all tree keys meet the criteria stated in the passed function
  • some(fn) verifies that at least one tree key meet the criteria stated in the passed function

Use the left-to-right order when traversing the tree. That is, first we process the node key, then the left child key, then the right child key.

Examples

const tree = new Node(9,
  new Node(4,
    new Node(8),
    new Node(6,
      new Node(3),
      new Node(7))),
  new Node(17,
    null,
    new Node(22,
      null,
      new Node(20))));

tree.getCount() // 9
tree.getSum(); // 96
tree.toArray(); // [9, 4, 8, 6, 3, 7, 17, 22, 20]
tree.toString(); // '(9, 4, 8, 6, 3, 7, 17, 22, 20)'

tree.every((key) => key <= 22); // true
tree.every((key) => key < 22); // false
tree.some((key) => key < 4); // true
tree.some((key) => key > 22); // false

Tips

  • Binary tree
  • To implement each of the methods, you will need to traverse all the tree nodes
  • Recall the reduce array method

For full access to the challenge you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests