Display n-ary tree recursively

I am trying to display an n-ary tree structure in a browser.

Here is an example of the data structure from which it is extracted:

var jsonObj = [{
    id: "window1", 
    name: "Corporate",
    children: [
        { id: "window12", name:"IT", children: [
            { id: "window121", name:"Dev", children: [] },
            { id: "window122", name:"Web", children: [] }
        ] }, 
        { id: "window13", name:"HR", children: [] }, 
        { id: "window14", name:"Finance", children: [] }
    ]
}];

I intend for it (structure, that is) to look like this tree (only side by side):

http://gravite.labri.fr/images/tidyTree.jpg

and currently it looks close http://imm.io/Dz3V , but not quite there.

Here is the algorithm I wrote that generated this conclusion:

var create_graph_components = function (json, level, offset) {
    for (var i = 0; i < json.children.length; i++) {
        offset += create_graph_components(json.children[i], level + 1, offset);
    }
    if (json.children.length == 0) {
        $('#wrapper').append("<div class=\"component window\" style=\"top:"+offset+"px;left: "+level*150+"px\" id=\""+json.id+"\"><strong>"+json.name+"</strong></div>");
        offset = 50;
    } else {
        $('#wrapper').append("<div class=\"component window\" style=\"top:"+offset/2+"px;left: "+level*150+"px\" id=\""+json.id+"\"><strong>"+json.name+"</strong></div>");
    }
    return offset;
};

All that does is add the divs to the page in the correct position, which is what I am having problems with.

Does anyone have an idea on how I could improve my algorithm to nicely print a tree closer to how I want it? I think I'm close, but lost ideas!

+1
source share
1

...

function create_graph_components(json, level, offsetStart) {

    var offsetEnd = offsetStart;

    for (var i = 0; i < json.children.length; i++) {
        offsetEnd = create_graph_components(json.children[i], level + 1, offsetEnd);
    }

    var offset;            
    if (json.children.length == 0) {
        offset = offsetEnd;            
        // Node is a leaf therefore extend offsetEnd
        offsetEnd += 50;
    } else {
        // Calculates position halfway between child nodes
        offset = offsetStart + (offsetEnd - offsetStart - 50) / 2;
        // Node is a branch therefore we do not extend the offsetEnd
    }

    // Create the element
    var child = $('<div id="' + json.id + '" class="component window">' +
                      '<strong>' + json.name + '</strong>' +
                  '</div>');

    // Position the element
    child.css({
        top: offset + "px",
        left: level * 150 + "px"
    });

    // Add it to the wrapper
    $("#wrapper").append(child);     

    return offsetEnd;

}

http://jsfiddle.net/j7Pms/

0

All Articles