T
T
tetieee2022-03-23 12:38:15
JavaScript
tetieee, 2022-03-23 12:38:15

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

3 answer(s)
R
rPman, 2022-03-23
@rPman

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

G
GrayHorse, 2022-03-23
@GrayHorse

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));

623aec3ba5b5c934945899.png

A
Alexandroppolus, 2022-03-23
@Alexandroppolus

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 question

Ask a Question

731 491 924 answers to any question