Thursday 15 March 2012

node.js - Recursive tree traversal in level order -


I have the following recurring data structure and a method runs on it. However, by doing so, a unique number on each node < Code> n should add its number of trees.

  var data = {children: [children: [...]}, {children: [...]}, {children: [. ..]}, ...]} var process = function (node) {node. Chilin EEF (child, function) (process (child);}); Return node; }   

How can I get the minimum change without changing the data structure and processing function? The result of the data should be

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

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

Initially, press the root node and null in the queue, again to the queue, Push the children of each node in the queue and mark the non-null element when you face a null element, then push a new one. Then the result of the end result of two result zero repetition.

  var process = function (node) {var queue = [node, null]; Var i = 0, n = 1; While (queue [i]! = Tap || (i == 0 || qi [ii]] = null) (if (q [i] == faucet) {q. Pice (null);} and {Queue [ii] .n = n ++; queue [i] for children (function (amm) {queue.push (elem);});} i ++;}} data processing); Console.log (data);   

I used an array for the queue and did not correspond to the required elements ( O (n) space) if Q < The space consumed by / code> is a hindrance, so you can replace it with the implementation of any other queue and can alter the algorithm a little bit.

No comments:

Post a Comment