Skip to content

Instantly share code, notes, and snippets.

@anton0xf
Last active February 9, 2016 11:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anton0xf/076a01c53ef1b5701fc2 to your computer and use it in GitHub Desktop.
Save anton0xf/076a01c53ef1b5701fc2 to your computer and use it in GitHub Desktop.
рещение задачи из https://gist.github.com/076a01c53ef1b5701fc2
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