JavaScript: Building binary tree
Last update: 18 Mar 23:20
0
Students
A binary tree is a hierarchical data structure in which each node has no more than two descendants (children). The first is the parent node, and the children are the left and right descendants.
In this exercise, we will use a subspecies of a binary tree — a binary search tree. The proper tree does not contain duplicate keys, and it garanties for each node that in the left subtree all values are less than the current one, and in the right one — more.
Node.js
Implement and export as default the class that represents the node.
The class must contain:
- The
getKey()
getter that returns the key - The
getLeft()
andGetRight()
getters that return the left and right child, respectively. If there are no child nodes, the getter returnsnull
- The
insert(key)
method adds a node, forming a correct binary tree
Examples
const tree = new Node();
tree.insert(9);
tree.insert(17);
tree.insert(4);
tree.insert(3);
tree.insert(6);
tree.getKey(); // 9
tree.getLeft().getKey(); // 4
tree.getRight().getKey(); // 17
tree.getLeft().getLeft().getKey(); // 3
tree.getLeft().getRight().getKey(); // 6
Tips
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.