Created
November 13, 2012 21:47
-
-
Save dherman/4068615 to your computer and use it in GitHub Desktop.
example of a context argument
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
function Tree(value, left, right) { | |
if (!(this instanceof Tree)) | |
return new Tree(value, left, right); | |
this.value = value; | |
this.left = left || null; | |
this.right = right || null; | |
} | |
Tree.prototype.toString = function toString() { | |
return "(" + JSON.stringify(this.value) + " " + this.left + " " + this.right + ")"; | |
}; | |
// An implementation that computes the max depth of a tree purely | |
// by reference to the results of sub-computations. | |
function maxDepth1(tree) { | |
return tree === null | |
? 0 | |
: Math.max(maxDepth1(tree.left), maxDepth1(tree.right)) + 1; | |
} | |
// An implementation that computes the max depth of a tree by | |
// carrying a context argument representing the current depth. | |
function maxDepth2(tree, depth) { | |
depth = depth || 0; | |
if (tree === null) | |
return depth; | |
return Math.max(maxDepth2(tree.left, depth + 1), | |
maxDepth2(tree.right, depth + 1)); | |
} | |
var t1 = Tree("foo", Tree("bar", Tree("baz")), Tree("quux")); | |
var t2 = null; | |
var t3 = Tree("mumble", t1, t1); | |
function test(tree, expected) { | |
console.log("test: " + tree); | |
var a1 = maxDepth1(tree), a2 = maxDepth2(tree); | |
console.log(a1 === expected && a2 === expected ? "PASSED" : "FAILED"); | |
console.log(); | |
} | |
test(t1, 3); | |
test(t2, 0); | |
test(t3, 4); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment