Search code examples
javascriptgraphtreetraversal

How to split a tree on all possible subtrees?


I'm trying to build an iterator on JS that will take a tree and on each iteration return next possible subtree.

Here is an example of source tree:

{
  name: 'A',
  children: [
    {
      name: 'B',
      children: [
        {
          name: 'E'
        },
        {
          name: 'F'
        },
      ]
    },
    {
      name: 'C',
    }
  ]
}

The result should be three iterations

1. {
  name: 'A',
  children: [ 
    { 
      name: 'B', 
      children: [ 
        {
          name: 'E'
        } 
      ]
    }
  ]
}

2. {
  name: 'A',
  children: [ 
    { 
      name: 'B', 
      children: [ 
        {
          name: 'F'
        } 
      ]
    }
  ]
}

3. {
  name: 'A',
  children: [ 
    { 
      name: 'C', 
    }
  ]
}

Could someone give me a hint or point to the right direction of how this problem could be solved?

Thanks!


Solution

  • I think recursive function is your answer.

    Something like this?

    (It worked using your example)

    var newtrees = [];
    
    var getTreeFromPath = function(path) {
       var newtree = {};
       var next = newtree;
       for (var i = 0 ; i < path.length;i++) {
           next.name = path[i].name;
           if (path[i].children) {
              var nextIteration = {};
              next.children = [nextIteration];
           }
           next = nextIteration;
       }
       return newtree;
    
    }
    var iterateNode = function(node, pathToNode) {
       if (!node.children) { 
           pathToNode.push(node);
           newtrees.push(getTreeFromPath(pathToNode));
       } else {
           pathToNode.push(node);
           for (var i = 0;i < node.children.length;i++) {
    
              iterateNode(node.children[i], pathToNode);
           }
       }
    };
    iterateNode(tree, []);