Created
November 20, 2014 18:49
-
-
Save coryk135/615617e9eb0c2c1b8eeb to your computer and use it in GitHub Desktop.
Fibonacci 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
function Branch(type, depth){ | |
this.branches = []; | |
this.type = type || 0; // 1 or 0 | |
this.depth = depth || 0; | |
} | |
Branch.prototype.grow = function(){ | |
if(this.branches.length == 0){ | |
if(this.type){ | |
this.branches.push(new Branch(0, this.depth+1)); | |
} | |
this.branches.push(new Branch(1, this.depth+1)); | |
} else { | |
for(var idx in this.branches){ | |
var b = this.branches[idx]; | |
b.grow(); | |
} | |
} | |
} | |
Branch.prototype.print = function(){ | |
var queue = [this]; | |
var stack = []; | |
var lastDepth = -1; | |
var s = 'depth 0:'; | |
while(queue.length){ | |
var v = queue.shift(); | |
if(v.depth != lastDepth){ | |
stack.push(s); | |
lastDepth = v.depth; | |
s = 'depth ' + v.depth + ':'; | |
} | |
s += ' ' + v.type; | |
for(var idx in v.branches){ | |
queue.push(v.branches[idx]); | |
} | |
} | |
stack.push(s); | |
var level = stack.pop().split(':')[1]; | |
var prevLen, len, padding, paddingStr = ''; | |
while(stack.length){ | |
prevLen = level.length; | |
console.log(paddingStr + level); | |
level = stack.pop().split(':')[1]; | |
len = level.length; | |
padding = (prevLen-len)/2 + 1; | |
while(padding-- && padding > 0) { paddingStr += ' '; } | |
} | |
} |
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
var root = new Branch(); | |
root.grow(); | |
root.grow(); | |
root.print(); | |
/* Output: | |
0 1 | |
1 | |
0 | |
*/ | |
root.grow(); | |
root.grow(); | |
root.print(); | |
/* Output: | |
0 1 1 0 1 | |
1 0 1 | |
0 1 | |
1 | |
0 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment