Created
November 13, 2014 14:34
-
-
Save jesslilly/a75fd3f348902aeca644 to your computer and use it in GitHub Desktop.
Some fun with trees
This file contains hidden or 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
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