如何在 R 中将层序树转换为预序树?

How do you convert from a level order tree to a preorder tree in R?

我有一个列表,表示按级别顺序遍历的树。

第一位是children的编号,第二位是它的“级别”,从1开始。

我希望程序输出一个列表,其元素与 matr 相同,但顺序不同。

Example

对于输入: 列表(c(4,1),c(0,2),c(2,2),c(0,2),c(1,2),c(0,3),c(0,3) , c(0,3))

输出应该是: 列表(c(4,1),c(0,2),c(2,2),c(0,3),c(0,3),c(0,2),c(1,2) , c(0,3))

我认为问题出在全局变量上?我已经在 Python 中使用了它,但据我所知他们在做同样的事情,但在 R 中却没有。

这是我的:

matr = list(c(4,1), c(0,2), c(2,2), c(0,2), c(1,2), c(0,3), c(0,3), c(0,3))
tot = 3
new = list()

func <- function(new, matr, level,tot){
 if (level <= tot){
   for (i in 1:length(matr)){
     if (matr[[i]][2] == level){
       a = matr[[i]]
       matr = matr[-i]
       new = c(new, list(a))
       break
     }
   }
   if (a[1]!=0){
     for (i in 1:a[1]){
       func(new,matr,level+1,tot)
     }
   }
 }
}
func(new, matr,1,tot)

作为参考,下面的代码可以满足我的要求(但它在 Python 而不是 R 中)

matr = [[4,1], [0,2], [2,2], [0,2], [1,2], [0,3], [0,3], [0,3]]
tot=3
newm = []
def func(newm, matr, level):
    if level <= tot:
        a = [k for k in matr if k[1] == level][0]
        newm.append(a)
        matr.remove(a)
        for i in range(a[0]):
            func(newm,matr,level+1)
func(newm, matr,1)
print(newm)

没关系 -- 解决了

if (level<=tot){
  for(i in 1:length(matr)){
    if (matr[[i]][2]==level){
      a = matr[[i]]
      assign("matr",matr[-i], envir=.GlobalEnv)
      break
    }
  }
  
  assign("newm", c(newm, list(a)), envir = .GlobalEnv)
  
  if (a[1]!=0){
    for (i in 1:a[1]){
      topreorder(level+1)
    }
  }
  
}