擅长:python、mysql、java
<p>这里可能有一个递归选项供您使用<code>data.frame</code>跟踪节点级别,即</p>
<pre><code>f <- function(sons) {
getTree <- function(s.df) {
repeat {
sons <- subset(
df,
father %in% s.df$sons[s.df$lvl == max(s.df$lvl)]
)[["son"]]
if (length(sons) == 0) {
return(s.df)
}
p <- data.frame(sons = sons, lvl = max(s.df$lvl) + 1)
s.df <- rbind(s.df, getTree(p))
}
}
getTree(data.frame(sons = sons, lvl = 0))
}
</code></pre>
<p>其中,输入参数<code>sons</code>的级别始终从<code>0</code>开始到函数<code>f</code>,这样</p>
<pre><code>> f(1)
sons lvl
1 1 0
2 2 1
3 3 1
4 4 2
5 6 2
6 7 3
7 9 3
> f(2)
sons lvl
1 2 0
2 4 1
3 6 1
4 7 2
5 9 2
> f(5)
sons lvl
1 5 0
2 8 1
</code></pre>