1

I get JSON string. And use function for create ul list.

How i can do it without recursion?

Thank anyone for help!

function createJsonTree(objData) {
    if (isChild(objData))
        return;

    var ul = createElem('ul');

    for (var i = 0, length = objData.length; i < length; i++) {
        if (i in objData) {
            var li = createElem('li');

            if (objData[i].dropmenu) {
                ...
            }

            var li = createElem('li');
            li.innerHTML = objData[i].NAMEGROUP;

            var childUl = createJsonTree(objData[i].dropmenu);

            if (childUl)
                li.appendChild(childUl);

            ul.appendChild(li);
        }
    }

    return ul;
}
6
  • 1
    Why do you need to create a tree without recursion? How do you plan on using a tree without recursion? Commented May 15, 2015 at 17:44
  • You can use a stack instead and iterate. Commented May 15, 2015 at 17:46
  • 2
    anything done recursively can be done iteratively. might end up being hideously ugly/inefficient, but doesn't mean it's impossible. Commented May 15, 2015 at 17:46
  • Because I want to learn to do it without recursion. With the help of the cycle, but does not work yet ( Commented May 15, 2015 at 18:34
  • @GanibalKing: Hint: recursion manages the stack/queue structure for you by using the call stack. If you want to do something recursive in a loop instead you need to manually manage the stack/queue using an array. Commented May 15, 2015 at 20:33

1 Answer 1

1

For "breath-first traversing", use a queue (first in first out). For "depth-first traversing", use a stack (last in first out)

Here is the pseudo code

// add the root node to the structure
// while the structure has elements in it
//    withdraw first element
//    add all it's children to the structure
//    do something with the element
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.