Skip to content

Instantly share code, notes, and snippets.

@aessam
Last active August 29, 2015 14:04
Show Gist options
  • Select an option

  • Save aessam/a2a3531ee3d6dfed9368 to your computer and use it in GitHub Desktop.

Select an option

Save aessam/a2a3531ee3d6dfed9368 to your computer and use it in GitHub Desktop.
Simple Tree structure functions (add to tree, get max, get min, get tree width)
#!/usr/local/bin/node
// If the incoming value > then add to left, if the value is < add to right
// if the left/right has value will go recursively until empty node is found
function addToTree(tree,v){
if(tree["v"] && tree["v"]!=v){
var direction = "";
if(tree["v"]>v) direction = "l";
if(tree["v"]<v) direction = "r";
if(tree[direction]==undefined){
tree[direction] = {};
}
addToTree(tree[direction],v);
}else{
tree["v"]=v;
}
}
// go recursivly in direction until there is no more nodes and return the value
function endLeafValue(tree,d){
if(tree[d]){
return endLeafValue(tree[d],d);
}
return tree["v"];
}
// Get minimum value in the tree
function getTreeMin(tree){
return endLeafValue(tree, "l");
}
// Get maximum value in the tree
function getTreeMax(tree){
return endLeafValue(tree, "r");
}
// How man steps does it take from root to the end leaf
function treeWidthForDirection(tree,d){
if(tree[d]){
return treeWidthForDirection(tree[d],d)+1;
}
return 0;
}
// Go to the far left and far right then calculate the steps between them
function treeWidth(tree){
return treeWidthForDirection(tree,"r") + treeWidthForDirection(tree,"l") + 1;
}
// check if there is something in the standard input to use it as data source
// in order to make use of the standard input, use something like cat for file contain
// data in form of lines, each line has integer.
if(process.stdin._readableState.highWaterMark>0){
process.stdin.setEncoding('utf8');
tree = {}
process.stdin.on('readable', function() {
var chunk = process.stdin.read();
if (chunk !== null) {
arr = chunk.split("\n");
for(item in arr){
if(arr[item].length>0){
addToTree(tree, parseInt(arr[item]));
}
}
}
});
process.stdin.on('end', function() {
console.log("Tree Width: " + treeWidth(tree));
console.log("Tree Min : " + getTreeMin(tree));
console.log("Tree Max : " + getTreeMax(tree));
console.log(JSON.stringify(tree));
});
}else{
rawTree = [ 10, 15, 5, 14, 17, 16, 9, 3, 1, 4 ];
tree = {}
for(item in rawTree){
addToTree(tree, rawTree[item]);
}
console.log("Tree Width: " + treeWidth(tree));
console.log("Tree Min : " + getTreeMin(tree));
console.log("Tree Max : " + getTreeMax(tree));
console.log(JSON.stringify(tree));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment