Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const NODE_COUNT = 5;
- function randomValue() {
- return Math.floor(Math.random() * 999) + 1;
- }
- function createWideTree() {
- var root = { parent: [{n: randomValue()}], children: [] };
- for(var i=1; root.children.length<=NODE_COUNT-1; i++) {
- root.children.push({ n: randomValue() });
- if(root.children.length >2){
- let removedChild = root.children.splice(1, 1);
- root.parent.push(removedChild[0]);
- if(root.parent.length >2){
- let removedParent = root.parent.splice(1, 1);
- createWideTree();
- }
- }
- }
- return root;
- }
- let root = createWideTree();
- function* traversalTree(root) {
- let arrRoot = [];
- let lastChild = '';
- let i;
- arrRoot.push(root);
- yield root;
- while (root) {
- if (root.children) {
- i = root.children.indexOf(lastChild);
- root = root.children[i+1];
- if (root) {
- lastChild = '';
- arrRoot.push(root);
- yield root;
- } else {
- lastChild = arrRoot.pop();
- root = arrRoot[arrRoot.length-1] || null;
- }
- } else {
- lastChild = arrRoot.pop();
- root = arrRoot[arrRoot.length-1] || null;
- }
- }
- }
- for(let node of traversalTree(root)) {
- console.log(node.n);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement