Advertisement
Guest User

Untitled

a guest
Apr 19th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const NODE_COUNT = 5;
  2.  
  3. function randomValue() {
  4.     return Math.floor(Math.random() * 999) + 1;
  5. }
  6.  
  7.  
  8. function createWideTree() {
  9.     var root = { parent: [{n:  randomValue()}], children: [] };
  10.     for(var i=1; root.children.length<=NODE_COUNT-1; i++) {
  11.         root.children.push({ n: randomValue() });
  12.         if(root.children.length >2){
  13.           let removedChild = root.children.splice(1, 1);
  14.           root.parent.push(removedChild[0]);
  15.           if(root.parent.length >2){
  16.             let removedParent = root.parent.splice(1, 1);
  17.             createWideTree();
  18.           }
  19.         }
  20.     }
  21.     return root;
  22. }
  23.    
  24. let root = createWideTree();
  25.  
  26.  
  27. function* traversalTree(root) {
  28.   let arrRoot = [];
  29.   let lastChild = '';
  30.   let i;
  31.    
  32.   arrRoot.push(root);  
  33.   yield root;
  34.  
  35.   while (root) {
  36.  
  37.      if (root.children) {
  38.      
  39.        i = root.children.indexOf(lastChild);
  40.        root = root.children[i+1];
  41.          
  42.        if (root) {
  43.           lastChild = '';
  44.           arrRoot.push(root);
  45.           yield root;            
  46.            
  47.        } else {
  48.           lastChild = arrRoot.pop();
  49.           root = arrRoot[arrRoot.length-1] || null;
  50.        }  
  51.      
  52.     } else {
  53.  
  54.       lastChild = arrRoot.pop();
  55.       root = arrRoot[arrRoot.length-1] || null;  
  56.     }  
  57.   }  
  58. }  
  59.  
  60. for(let node of traversalTree(root)) {
  61.     console.log(node.n);
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement