JSFiddle - React, Tailwind, and code Playground

by infous

HTML

<textarea style="width:100%" rows="20"></textarea>
<!-- https://habrahabr.ru/post/276673/ -->

JavaScript

function Node (data) {
	var left = null,
  	right = null;
    
  this.setLeft = function (data) { left = data; };
  this.getLeft = function () { return left; };
  this.setRight = function (data) { right = data; };
  this.getRight = function () { return right; };
  this.hasLeft = function () { return left !== null; };
  this.hasRight = function () { return right !== null; };
  
  this.data = data;
  
  this.nextSibling = null;
}

var n1 = new Node(1);
var n2 = new Node(2);
var n3 = new Node(3);
var n4 = new Node(4);
var n5 = new Node(5);
var n6 = new Node(6);
var n7 = new Node(7);

n1.setLeft(n2);
n1.setRight(n3);

n2.setLeft(n4);
n2.setRight(n5);

n3.setLeft(n6);
n3.setRight(n7);

var t = $("textarea");

function printNodes(nodes) {
	var newNodes = [];
  
	for (var i = 0; i < nodes.length; i++) {
  	var node = nodes[i];
    
    t.text(t.text() + node.data + "  ");
    
    if (node.hasLeft()) { newNodes.push(node.getLeft()); }
    if (node.hasRight()) { newNodes.push(node.getRight()); }
  }
  
  if (newNodes.length) {
  	t.text(t.text() + "\n");
  	printNodes(newNodes);
  }
}

function linkNodes(nodes) {
	var newNodes = [];
  
	for (var i = 0; i < nodes.length; i++) {
  	var node = nodes[i];
    
    if (i > 0) {
    	nodes[i -1].nextSibling = node;
    }
    
    if (node.hasLeft()) { newNodes.push(node.getLeft()); }
    if (node.hasRight()) { newNodes.push(node.getRight()); }
  }
  
  if (newNodes.length) {
  	linkNodes(newNodes);
  }
}

function printLinkedNodes(node) {
	var nextChild = null;
  
	do {
  	t.text(t.text() + node.data + "  ");
    
    if (!nextChild && node.hasLeft()) { nextChild = node.getLeft(); }
    if (!nextChild && node.hasRight()) { nextChild = node.getRight(); }
    
    node = node.nextSibling;
  } while (node);
  
  if (nextChild) {
  	t.text(t.text() + "\n");
  	printLinkedNodes(nextChild);
  }
}

printNodes([n1]);
linkNodes([n1]);
t.text(t.text() + "\n\n");
printLinkedNodes(n1);