N
N
netz-sanya2019-06-23 02:00:04
go
netz-sanya, 2019-06-23 02:00:04

What algorithm should be used to build a nested tree?

There is an array like this:

[{
    "Level": 0,
    "Val": "1"
}, {
    "Level": 0,
    "Val": "2"
}, {
    "Level": 1,
    "Val": "2.1"
}, {
    "Level": 1,
    "Val": "2.2"
}, {
    "Level": 2,
    "Val": "2.2.1"
}, {
    "Level": 3,
    "Val": "2.2.1.1"
}, {
    "Level": 0,
    "Val": "3"
}, {
    "Level": 1,
    "Val": "3.1"
}]

It needs to be converted to a tree like this:
[{
    "Level": 0,
    "Val": "1",
    "Children": []
}, {
    "Level": 0,
    "Val": "2",
    "Children": [{
        "Level": 1,
        "Val": "2.1",
        "Children": []
    }, {
        "Level": 1,
        "Val": "2.2",
        "Children": [{
            "Level": 2,
            "Val": "2.2.1",
            "Children": [{
                "Level": 3,
                "Val": "2.2.1.1",
                "Children": []
            }]
        }]
    }]
}, {
    "Level": 0,
    "Val": "3",
    "Children": [{
        "Level": 1,
        "Val": "3.1",
        "Children": []
    }]
}]

I can't figure out how to convert.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Q
qqrm, 2019-07-02
@qqrm

Perhaps you should use the tree implementation at the link
https://godoc.org/github.com/erriapo/redblacktree

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question