class Tree {
constructor(root) {
this.root = root;
}
Draw(where) {
let $el = $(where),
$node = $('<div/>', {
class: 'node root'
});
$node.appendTo($el);
Tree._Draw(this.root, $node);
}
static _Draw(root, $node) {
let $left,
$right;
$node.append(
$('<span/>', {
class: 'data'
}).text(root.data)
);
if (root.left || root.right) {
$node.append($('<hr/>'));
}
if (root.left) {
$left = $('<span/>', {
class: 'node left'
});
$node.append($left);
Tree._Draw(root.left, $left);
}
if (root.right) {
$right = $('<span/>', {
class: 'node right'
});
$node.append($right);
Tree._Draw(root.right, $right);
}
}
// Inorder method doesn't need a root argument now
// It uses instance's own root
Inorder() {
// Fire up the recursion
Tree._Inorder(this.root);
}
// Private part for the Inorder method's recursion
// It can be static since it will receive the root
// for each iteration
static _Inorder(root) {
if (root == null) {
return;
}
Tree._Inorder(root.left);
console.log(root.data);
Tree._Inorder(root.right);
}
}
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
const obj = new Node(5);
obj.left = new Node(10);
obj.right = new Node(15);
obj.left.left = new Node(16);
obj.right.right = new Node(17);
obj.right.left = new Node(8);
const tree = new Tree(obj);
console.log("Tree created with root:", tree.root.data);
// Now we can call the inorder list for the tree
// without explicitely specifying the root node
tree.Inorder();
tree.Draw('#tree');
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.