Reputation: 137
I'm stuck when doing my homework. I need to convert my js binary-tree to Html+css, without using any hmtl code. Only vanilla js.
I got tree and recursive function that adding all tree elment to page, but i need it to be like ul, li.
const Node = {
data: 10,
left: {
data: 1,
left: null,
right: null
},
right: {
data: 7,
left: {
data: 6,
left: {
data: 4,
left: null,
right: null
},
right: null
},
rigth: null
}
};
const breadthFirst = function (node) {
function bf(queue) {
let newQueue = [];
queue.forEach(function (node) {
console.log(node.data);
const newEl = document.createElement('div');
newEl.innerText = node.data;
document.getElementById("app").appendChild(newEl)
node.left && newQueue.push(node.left);
node.right && newQueue.push(node.right);
});
newQueue.length && bf(newQueue);
}
bf([node]);
};
breadthFirst(Node);
So i've got all elments in column, but need to be like ordered list:
and etc.
Upvotes: 1
Views: 607
Reputation: 3638
In order to build up the multi-level structure of your tree you will need to append the sub elements to their parents. I seperated this to 2 functions.
const data = {
data: 10,
left: {
data: 1,
left: null,
right: null
},
right: {
data: 7,
left: {
data: 6,
left: {
data: 4,
left: null,
right: null
},
right: null
},
rigth: null
}
};
const createListItem = (treeNode) => {
if (!treeNode) {
return;
}
let item, subTree;
item = document.createElement('li');
item.textContent = treeNode.data;
subTree = createSubTreeForNode(treeNode);
if (subTree) {
item.appendChild(subTree);
}
return item;
};
const createSubTreeForNode = (treeNode) => {
if (!treeNode.left && !treeNode.right) {
return;
}
let list, item;
list = document.createElement('ul');
item = createListItem(treeNode.left);
if (item) {
list.appendChild(item);
}
item = createListItem(treeNode.right);
if (item) {
list.appendChild(item);
}
return list;
};
const renderTree = (treeNode, parentElement) => {
parentElement = parentElement || document.getElementById("app");
let rootList, item;
rootList = document.createElement('ul');
item = createListItem(treeNode);
if (item) {
rootList.appendChild(item);
}
parentElement.appendChild(rootList);
};
renderTree(data);
<div id="app"></div>
Upvotes: 1