Created
November 5, 2014 17:14
-
-
Save jondlm/5e6e2534afe0916af698 to your computer and use it in GitHub Desktop.
Javascript Trees
This file contains 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
var util = require('util'); | |
function TreeNode(data) { | |
this.data = data; | |
this.children = []; | |
} | |
TreeNode.prototype.isLeaf = function() { | |
return this.children.length === 0; | |
}; | |
TreeNode.prototype.addChild = function(c) { | |
this.children.push(c); | |
}; | |
TreeNode.prototype.show = function() { | |
console.log(util.inspect(this, {depth: 20})); | |
}; | |
TreeNode.prototype.preorder = function() { | |
console.log('%s %s', this.data, this.isLeaf()); | |
this.children.forEach(function(node) { | |
node.preorder(); | |
}); | |
}; | |
TreeNode.prototype.levelorder = function() { | |
var q = []; | |
q.push(this); | |
while (q.length > 0) { | |
var node = q.shift(); | |
console.log('%s %s', node.data, node.isLeaf()); | |
node.children.forEach(function(c) { | |
q.push(c); | |
}); | |
} | |
}; | |
// 1 | |
// / \ | |
// / \ | |
// / \ | |
// 2 3 | |
// / \ / | |
// 4 5 6 | |
// / /|\ | |
// 7 / | \ | |
// 8 9 10 | |
var one = new TreeNode(1); | |
var two = new TreeNode(2); | |
var three = new TreeNode(3); | |
var four = new TreeNode(4); | |
var five = new TreeNode(5); | |
var six = new TreeNode(6); | |
var seven = new TreeNode(7); | |
var eight = new TreeNode(8); | |
var nine = new TreeNode(9); | |
var ten = new TreeNode(10); | |
one.addChild(two); | |
one.addChild(three); | |
two.addChild(four); | |
two.addChild(five); | |
four.addChild(seven); | |
three.addChild(six); | |
six.addChild(eight); | |
six.addChild(nine); | |
six.addChild(ten); | |
one.show(); | |
console.log('Depth first, preorder:'); | |
one.preorder(); | |
console.log('Bredth first, level-order:'); | |
one.levelorder(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment