Understanding the recursive build of trees(data.tree) in R

371 Views Asked by At

I am trying to build trees recursively in R using data.tree package. Anyone who is answering please understand recursion below. The code below contains only two levels of recursion. In the second level recursion I printed the tree structure (marked the print statement in my code for reference), it is similar the image below.

enter image description here

After the entire completion of code the tree structure is.enter image description here

I do not understand how the tree from level-2 recursion perfectly merged with the tree from level-1.

library(data.tree)
library(visNetwork)

recurs=function(i,previous_iteration_tree)
{
  if(i<=6)
  {
    if(i==1)
    {
      tree<-Node$new(i)
      tree$AddChild(i+1)
      tree$AddChild(i+2)
      tree$AddChild(i+3)
      tree$AddChild(i+4)
    }
    if(i==6)
    {
      dummy<-FindNode(previous_iteration_tree,i-4)
      a=dummy$AddChild(i)
      tree=a

      print(tree)#<------------------HERE
      #see the tree here
    }
  }
  else
    return(0)

  recurs(i+5,tree)

  plot(tree)
}

recurs(1,0)

Please help me out in this case!

0

There are 0 best solutions below