Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Some fun with trees
window.addEventListener('load', function(e) {
var trees = new Array(3);
trees[0] = {}; // 0 0
trees[1] = {a : {}}; // 1 1
trees[2] = {a : {}, b: {a : {}, b: {a : {}, b: {}}}}; // 6 3
var nodes = function(tree) {
var count = 0;
var nodes2 = function(tree) {
if (tree.a) {
count++;
nodes2(tree.a);
}
if (tree.b) {
count++;
nodes2(tree.b);
}
};
nodes2(tree);
return count;
};
var depth = function(tree) {
var max = -1;
var cur = -1;
var depth2 = function(tree) {
cur++;
if (cur > max) {max = cur;}
if (tree.a) {
depth2(tree.a);
}
if (tree.b) {
depth2(tree.b);
}
cur--;
};
depth2(tree);
return max;
};
var answer = "";
answer += "counts ";
answer += nodes(trees[0]);
answer += nodes(trees[1]);
answer += nodes(trees[2]);
answer += " depths ";
answer += depth(trees[0]);
answer += depth(trees[1]);
answer += depth(trees[2]);
document.querySelector('#test').innerHTML = "answer " + answer;
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment