Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jesslilly
Created November 13, 2014 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jesslilly/a75fd3f348902aeca644 to your computer and use it in GitHub Desktop.
Save jesslilly/a75fd3f348902aeca644 to your computer and use it in GitHub Desktop.
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