Skip to content

Commit

Permalink
Adding a very simple (and inefficient) depth calculation.
Browse files Browse the repository at this point in the history
  • Loading branch information
isaacs committed Jun 9, 2009
1 parent 35d1e54 commit 6e9ac64
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions data-structures/binary-search-tree/binary-search-tree.js
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -74,11 +74,17 @@ BinarySearchTree.prototype = {
contains : function (n) { contains : function (n) {
return this.find(n) !== undefined; return this.find(n) !== undefined;
}, },
depth : function () {
var d = 0;
this.traverse(function (_, depth) { if (depth > d) d = depth; });
return d;
},
// Call the supplied function on each node in ascending order. // Call the supplied function on each node in ascending order.
traverse : function (fn) { traverse : function (fn) {
if (this.left !== undefined) this.left.traverse(fn); var depth = arguments[1] || 0;
if (this.value !== undefined) fn.call(this, this.value); if (this.left !== undefined) this.left.traverse(fn, depth + 1);
if (this.right !== undefined) this.right.traverse(fn); if (this.value !== undefined) fn.call(this, this.value, depth);
if (this.right !== undefined) this.right.traverse(fn, depth + 1);
}, },
toArray : function (omitSelf) { toArray : function (omitSelf) {
var arr = []; var arr = [];
Expand Down

0 comments on commit 6e9ac64

Please sign in to comment.