Published
Edited
Apr 25, 2020
Insert cell
Insert cell
Insert cell
{
console.log('Preorder traversal:');
tree.preOrderTraverse();
}
Insert cell
{
console.log('Inorder traversal, sorted ASC:');
tree.inOrderTraverse();
}
Insert cell
{
console.log('Postorder traversal:');
tree.postOrderTraverse();
}
Insert cell
Insert cell
Insert cell
class Tree {
constructor(rootVal) {
if (rootVal !== null && !isNaN(rootVal)) {
this.root = new Node(rootVal);
} else {
this.root = null;
}
}

add(val) {
if (isNaN(val) || val === null) {
throw "Error adding value to a tree: value must be a number";
}

if (this.root === null) {
this.root = new Node(val);
} else {
this.root.add(val);
}
}

preOrderTraverse() {
if (this.root === null) {
return "empty tree";
}

this.root.preOrder();
}

inOrderTraverse() {
if (this.root === null) {
return "empty tree";
}

this.root.inOrder();
}

postOrderTraverse() {
if (this.root === null) {
return "empty tree";
}

this.root.postOrder();
}
}
Insert cell
class Node {
constructor(val) {
if (!isNaN(val) && val != null) {
this.value = val;
} else {
throw "Error constructing Node instance: must pass a number to a Node";
}
this.left = null;
this.right = null;
}

add(val) {
if (this.value > val) {
if (this.left === null) {
this.left = new Node(val);
} else {
this.left.add(val);
}
}
if (this.value < val) {
if (this.right === null) {
this.right = new Node(val);
} else {
this.right.add(val);
}
}
}

preOrder() {
console.log(this.value);
if (this.left !== null) {
this.left.preOrder();
}
if (this.right !== null) {
this.right.preOrder();
}
}

inOrder() {
if (this.left !== null) {
this.left.inOrder();
}
console.log(this.value);
if (this.right !== null) {
this.right.inOrder();
}
}

postOrder() {
if (this.left !== null) {
this.left.postOrder();
}
if (this.right !== null) {
this.right.postOrder();
}
console.log(this.value);
}
}
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more