Skip to content

Instantly share code, notes, and snippets.

@jondlm

jondlm/trees.js

Created Nov 5, 2014
Embed
What would you like to do?
Javascript Trees
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
You can’t perform that action at this time.