Recursive tree traversal in level order

强颜欢笑 提交于 2019-12-06 14:17:45

问题


I have the following recursive data structure and a method iterating over it. Whilst doing so it should add a unique number n to each node e.g. its respective number in level order traversal of the tree.

var data = {
    children: [
        { children: [ ... ] },
        { children: [ ... ] },
        { children: [ ... ] },
        ...
    ]
}

var process = function (node) {
    node.children.forEach(child, function () {
        process(child);
    });
    return node;
}

How can I achieve this without changes to the data structure and minimal changes to the processing function? Result of process(data) should be

var data = {
    n: 1
    children: [
        { n: 2, children: [ ... ] },
        { n: 3, children: [ ... ] },
        { n: 4, children: [ ... ] },
        ...
    ]
}

回答1:


Use a queue to store nodes at each level. Use null to mark the end of one level.

Initially, push the root node and null to the queue. Then iterate the queue, push children of each node to the queue and mark non-null element. When you encounter a null element, push a new one. So two consequent null marks the end of iteration.

var process = function (node) {
    var queue = [node, null];
    var i = 0, n = 1;
    while (queue[i] != null || (i == 0 || queue[i-1] != null)) {
        if (queue[i] == null) {
            queue.push(null);
        }
        else {
            queue[i].n = n++;
            queue[i].children.forEach(function (elem) {
                queue.push(elem);
            });
        }
        i++;
    }
}

process(data);
console.log(data);

I used an Array for the queue and didn't dequeue the visited elements (O(n) space required). If the space consumed by queue is a bottleneck, you can replace it with some other queue implementation and alter the algorithm a bit.



来源:https://stackoverflow.com/questions/17244930/recursive-tree-traversal-in-level-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!