Skip to content

Instantly share code, notes, and snippets.

@siwalikm
Last active March 21, 2021 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save siwalikm/3f2084f4f28c6ce851b019b5cd743017 to your computer and use it in GitHub Desktop.
Save siwalikm/3f2084f4f28c6ce851b019b5cd743017 to your computer and use it in GitHub Desktop.
Trinary tree in js
// Implementing insert and delete methods in a tri-nary tree. Much like a
// binary-tree but with 3 child nodes for each parent instead of two -- with the
// left node being values < parent, the right node values > parent, and the middle node
// values == parent.
function Node(val) {
this.value = val;
this.center = null;
this.left = null;
this.right = null;
}
function Ttree() {
this.root = null;
}
Ttree.prototype.insert = function (val) {
var root = this.root;
if (!root) {
this.root = new Node(val);
return;
}
var currentNode = root;
var newNode = new Node(val);
while (currentNode) {
if (val < currentNode.value) {
if (!currentNode.left) {
currentNode.left = newNode;
break;
} else {
currentNode = currentNode.left;
}
} else if (val > currentNode.value) {
if (!currentNode.right) {
currentNode.right = newNode;
break;
} else {
currentNode = currentNode.right;
}
} else {
if (!currentNode.center) {
currentNode.center = newNode;
break;
} else {
currentNode = currentNode.center;
}
}
}
};
Ttree.prototype.delete = function (val) {
if (!this.root) {
return;
}
var currentNode = this.root;
var newNode = new Node(null);
while (currentNode) {
if (val < currentNode.value) {
if (!currentNode.left) {
currentNode.left = newNode;
break;
} else {
currentNode = currentNode.left;
}
} else if (val > currentNode.value) {
if (!currentNode.right) {
currentNode.right = newNode;
break;
} else {
currentNode = currentNode.right;
}
} else {
if (!currentNode.center) {
currentNode.center = newNode;
break;
} else {
currentNode = currentNode.center;
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment