Last active
February 9, 2016 11:16
-
-
Save anton0xf/076a01c53ef1b5701fc2 to your computer and use it in GitHub Desktop.
рещение задачи из https://gist.github.com/076a01c53ef1b5701fc2
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 Node(data, left, right) { | |
this.data = data; | |
this.left = left || null; | |
this.right = right || null; | |
this.neighbour = null; | |
} | |
Node.prototype.toString = function() { | |
return "(" + this.data | |
+ " [" + (this.left || ".") + " " + (this.right || ".") + "]" | |
+ (this.neighbour ? " -> " + this.neighbour.data : "") | |
+ ")"; | |
} | |
function fill_neighbours(root) { | |
var cur_layer = [root]; | |
while(cur_layer.length > 0) { | |
var next_layer = []; | |
for(var i=0; i < cur_layer.length; i++) { | |
var cur_node = cur_layer[i]; | |
// connect elements of current layer | |
if(i>0) { | |
cur_layer[i-1].neighbour = cur_node; | |
} | |
// fill next layer | |
cur_node.left && next_layer.push(cur_node.left) | |
cur_node.right && next_layer.push(cur_node.right) | |
} | |
cur_layer = next_layer; | |
} | |
} | |
var root = new Node(1, | |
new Node(2, new Node(4)), | |
new Node(3, new Node(6), new Node(7))); | |
console.log("tree before: " + root); | |
fill_neighbours(root); | |
console.log("tree after: " + root); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment