Answer the question
In order to leave comments, you need to log in
How to represent a tree as an array?
Hello. how to represent a tree as a flat array?
Answer the question
In order to leave comments, you need to log in
what is the question if the answer is in the tags? recursion
out id even ready, contain the identifier of the ancestor
stupidly run through all the branches of the tree, adding identifiers to the resulting array
function * flat(target) {
yield target;
if (target.children?.length) {
for (const child of target.children) {
yield * flat(child);
}
}
}
const target = {};
console.log([...flat(target)]); // Array.from(flat(target));
What kind of tree do you have there?
For example, if this is a balanced binary tree, then you can use the approach as here.
If something else, then you need to look at what exactly.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question