Last active
March 21, 2021 08:39
-
-
Save siwalikm/3f2084f4f28c6ce851b019b5cd743017 to your computer and use it in GitHub Desktop.
Trinary tree in js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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