JSFiddle - React, Tailwind, and code Playground
by Aaron Zhang
HTML
<div id="tree"></div>
JavaScript
(function (window) {
function Node(val) {
this.value = val;
}
function Tree(val) {
this.root = new Node(val);
}
function dfs(currentNode, layerDict, currentLevel) {
layerDict[currentLevel] = layerDict[currentLevel] || [];
layerDict[currentLevel].push(currentNode);
var left = currentNode.left;
var right = currentNode.right;
if (left) {
dfs(left, layerDict, currentLevel + 1);
}
if (right) {
dfs(right, layerDict, currentLevel + 1);
}
return layerDict;
}
Tree.prototype.DFS = function () {
return dfs(this.root, {}, 0);
};
function dfsJson(jsonObj) {
var node = new Node(jsonObj.value);
if (jsonObj.left) {
node.left = dfsJson(jsonObj.left);
node.left.parent = node;
}
if (jsonObj.right) {
node.right = dfsJson(jsonObj.right);
node.right.parent = node;
}
return node;
}
Tree.fromJSON = function (jsonObj) {
var tree = new Tree();
tree.root = dfsJson(jsonObj);
return tree;
};
window.Node = Node;
window.Tree = Tree;
})(window);
(function () {
'use strict';
String.prototype.appendSpace = function (numSpaces) {
var copy = this;
for (var i = 0; i < numSpaces; ++i) {
copy += ' ';
}
return copy;
};
})();
(function () {
'use strict';
var jsonTree = {
value: 'root',
left: {
value: '1',
left: {
value: '2'
},
right: {
value: '3'
}
},
right: {
value: '4',
left: {
value: '5',
left: {
value: '6'
},
right: {
value: '7'
}
}
}
};
var tree =...