Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Adding a very simple (and inefficient) depth calculation.

  • Loading branch information...
commit 6e9ac6417d8a94b3eefc6b54705df87816d8c3bd 1 parent 35d1e54
isaacs authored
Showing with 9 additions and 3 deletions.
  1. +9 −3 data-structures/binary-search-tree/binary-search-tree.js
View
12 data-structures/binary-search-tree/binary-search-tree.js
@@ -74,11 +74,17 @@ BinarySearchTree.prototype = {
contains : function (n) {
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.
traverse : function (fn) {
- if (this.left !== undefined) this.left.traverse(fn);
- if (this.value !== undefined) fn.call(this, this.value);
- if (this.right !== undefined) this.right.traverse(fn);
+ var depth = arguments[1] || 0;
+ if (this.left !== undefined) this.left.traverse(fn, depth + 1);
+ if (this.value !== undefined) fn.call(this, this.value, depth);
+ if (this.right !== undefined) this.right.traverse(fn, depth + 1);
},
toArray : function (omitSelf) {
var arr = [];
Please sign in to comment.
Something went wrong with that request. Please try again.