JavaScript Lab - Articles - Non-recursive Preorder Traversal - Part 4
Non-recursive Preorder Traversal - Part 4
Published on 18th of December 2009. Copyright Tavs Dokkedahl. Displayed 6416 time(s)Different kind of traversals
Preorder is just one way of traversing a tree. Postorder and levelorder is two different approaches. There also exist inorder traversal but that is only well defined for binary trees and is thus not very usefull for DOM trees.
Non-recursive postorder traversal
In a postorder traversal the nodes are visited in the following order
Again the red numbers indicates when the node is visited but not processed. A non-recursive algorithm for postorder traversal is
1 function postorderTraversal(root) { 2 var n = root; 3 while(n) { 4 // Find first left most leaf on a path which have not 5 // yet been visited 6 if (n.firstChild && !n.v) { 7 // Mark node as visited 8 n.v = true; 9 n = n.firstChild; 10 } 11 else { 12 // 13 // Do something with node 14 // 15 // If n is root node, traversal is complete so break loop 16 if (n == root) 17 break; 18 // Find next node 19 if (n.nextSibling) 20 n = n.nextSibling; 21 else 22 n = n.parentNode; 23 } 24 } 25 }As you can see it is not much different from the preorder algorithm although slightly more simple.
Levelorder traversal
The final form of traversal is levelorder traversal. Levelorder traversal visits the nodes as they are ordered according to the level in the tree.
The easiest way to implement levelorder without recursion is to use a queue.
1 // Non-recursive levelorder traversal of DOM tree 2 function levelorderTraversal(root) { 3 // Initialize queue to contain root element 4 var q1 = [root]; 5 // While there are elements in the queue 6 while(q1.length) { 7 var q2 = []; 8 // For each element in queue 9 for(var i=0; i<q1.length; i++) { 10 // 11 // Do something with node q[i] 12 // 13 // Create new queue with childnodes of elements in queue 14 for(var j=0; j<q1[i].childNodes.length; j++) 15 q2.push(q1[i].childNodes[j]); 16 } 17 q1 = q2; 18 } 19 }I never really had the need for anything besides preorder traversal but if you can think of some common places where one could utilize postorder or levelorder concerning DOM trees please leave a comment.